blob: 36f1e9adb9270e530008dbaef5d80c6fe85c8397 (
plain)
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
|
/*
* g1 and g2 here are "references to the m1/m2 variables,
* I believe they do not point directly to the data address,
* but to the variables addresses.
*
* This makes greet to 'borrow' the reference to the strings,
* and once the greet() stackframe is gone, m1 and m2 are not
* freed, just g1 and g2. And since they don't own anything,
* nothing in the heap is freed.
*/
fn greet(g1: &String, g2: &String) {
println!("{} {}", *g1, *g2);
}
fn crazy_ref() {
let x: Box<i32> = Box::new(-1);
let x_abs1 = i32::abs(*x);
let x_abs2 = x.abs();
assert_eq!(x_abs1, x_abs2);
let r: &Box<i32> = &x;
let r_abs1 = i32::abs(**r);
let r_abs2 = r.abs();
assert_eq!(r_abs1, r_abs2);
let s = String::from("Howdy");
let s_len1 = str::len(&s);
let s_len2 = s.len();
assert_eq!(s_len1, s_len2);
}
fn main() {
let m1 = String::from("Howdy");
let m2 = String::from("partner");
/*
* Pass a reference to m1 and m2 to the function parameters.
*/
greet(&m1, &m2);
crazy_ref();
}
|