summaryrefslogtreecommitdiff
path: root/rust/chap4/borrow.rs
diff options
context:
space:
mode:
authorCarlos Maiolino <[email protected]>2025-09-06 09:30:14 +0200
committerCarlos Maiolino <[email protected]>2025-09-06 09:30:14 +0200
commit93b1c04a218858ecc59b6b8929103695b7b8c2a0 (patch)
tree7ae24ff4b2ef06c8d961f2c908ba8511e1fc995b /rust/chap4/borrow.rs
parent973e27b243ea7f12b6743894465c67a4a6a87eb2 (diff)
Move rust playground here
Signed-off-by: Carlos Maiolino <[email protected]>
Diffstat (limited to 'rust/chap4/borrow.rs')
-rw-r--r--rust/chap4/borrow.rs44
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();
+
+}