diff options
Diffstat (limited to 'rust/chap4/borrow.rs')
| -rw-r--r-- | rust/chap4/borrow.rs | 44 |
1 files changed, 44 insertions, 0 deletions
diff --git a/rust/chap4/borrow.rs b/rust/chap4/borrow.rs new file mode 100644 index 0000000..36f1e9a --- /dev/null +++ b/rust/chap4/borrow.rs @@ -0,0 +1,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(); + +} |
