-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscratch_vec.rs
executable file
·55 lines (51 loc) · 2.14 KB
/
scratch_vec.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#!/usr/bin/env -S cargo +nightly -Zscript
---
package.edition = "2024"
[dependencies]
---
//! # Vec : just playing with with some vector methods.
fn main() {
// Swap_Remove
{
println!("Hello from a rust script!");
let mut vv = vec!['a','b','c'];
println!("swap_remove(0): {}", vv.swap_remove(0));
println!("last is first: {:?}", vv);
println!("swap_remove(1): {}", vv.swap_remove(1));
// println!("swap_remove(1): {}", vv.swap_remove(1)); <-- would panic, out of bounds}
println!("swap_remove(0): {}", vv.swap_remove(0)); // <-- allowed despite lack of element to swap in
// println!("swap_remove(0): {}", vv.swap_remove(0)); // <-- would panic, out of bounds}
}
// Leak
{
let ref_to_forever = {
let vv = vec!['a', 'b', 'g'];
vv.leak()
};
println!("leaked ref: {:?}", ref_to_forever);
ref_to_forever.swap(0,2);
println!("leaked ref: {:?}", ref_to_forever);
std::thread::spawn(move|| {
for c in ref_to_forever {
eprintln!("from thread: {}", c);
}
});
// // Won't live long enough!
// let mut regular_lifetime = {
// let mut vv = vec!['a', 'b', 'g'];
// &mut vv
// };
let mut vv = vec!['A', 'B', 'G'];
let regular_lifetime = &mut vv;
println!("leaked ref: {:?}", regular_lifetime);
regular_lifetime.swap(0,2);
println!("leaked ref: {:?}", regular_lifetime);
// // Won't live long enough!
// std::thread::spawn(|| {
// for c in regular_lifetime{
// println!("from thread: {}", c);
// }
// });
std::thread::sleep(std::time::Duration::from_millis(10));
}
}