From 869e68986aa8f69af6e7842260a68d1e5c6f796f Mon Sep 17 00:00:00 2001 From: Carlos Maiolino Date: Thu, 10 Jul 2025 22:24:20 +0200 Subject: Add a bunch of code Signed-off-by: Carlos Maiolino --- rust/refs_and_borrows/Cargo.lock | 7 +++++ rust/refs_and_borrows/Cargo.toml | 8 +++++ rust/refs_and_borrows/src/main.rs | 62 +++++++++++++++++++++++++++++++++++++++ 3 files changed, 77 insertions(+) create mode 100644 rust/refs_and_borrows/Cargo.lock create mode 100644 rust/refs_and_borrows/Cargo.toml create mode 100644 rust/refs_and_borrows/src/main.rs (limited to 'rust/refs_and_borrows') diff --git a/rust/refs_and_borrows/Cargo.lock b/rust/refs_and_borrows/Cargo.lock new file mode 100644 index 0000000..cf9d7bd --- /dev/null +++ b/rust/refs_and_borrows/Cargo.lock @@ -0,0 +1,7 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "refs_and_borrows" +version = "0.1.0" diff --git a/rust/refs_and_borrows/Cargo.toml b/rust/refs_and_borrows/Cargo.toml new file mode 100644 index 0000000..76c4f89 --- /dev/null +++ b/rust/refs_and_borrows/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "refs_and_borrows" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/rust/refs_and_borrows/src/main.rs b/rust/refs_and_borrows/src/main.rs new file mode 100644 index 0000000..212372b --- /dev/null +++ b/rust/refs_and_borrows/src/main.rs @@ -0,0 +1,62 @@ +fn main() { + let m1 = String::from("Hello"); + let m2 = String::from("world"); + + // Borrow m1 and m2 references to greet(), instead of passing ownership + greet(&m1, &m2); + let s = format!("{} {}", m1, m2); + println!("{s}"); + +// fing_it(); +// aliasing_bonanza(); +// mutable_bonanza(); + flow_me(); +} + +// g1 is a reference that points to m1 on the stack, and m1 is a String +// containing a box, pointing to "Hello" string on the heap. +fn greet(g1: &String, g2: &String) -> () { + println!("Greet: {}, {}", *g1, *g2); +} + +fn fing_it() -> () { + let mut x: Box = Box::new(1); + let _a:i32 = *x; + *x += 1; + + let ref1: Box = Box::new(-5); + + println!("This is sparta: {}", i32::abs(*ref1)); +} + +/* +fn aliasing_bonanza() -> () { + let mut v: Vec = vec![10, 20, 30]; + let num: &i32 = &v[2]; + v.push(40); + + println!("{:?}", *num) +} +*/ +fn mutable_bonanza() -> () { + let mut v: Vec = vec![10, 20, 30]; + + // let mut makes the VAR mutable, i.e. it can be reassigned + // let :&mut i32 = &mut foo creates an IMMUTABLE that points to a + // mutable memory + + let num: &mut i32 = &mut v[2]; + let num2: &i32 = num; + + println!("Index 2 == {}", *num2); +} + +// Yes, moving { to the next line on purpose +fn flow_me(strings: &Vec, default: &String) -> &String +{ + if strings.len() > 0 { + &strings[0] + } else { + default + } +} -- cgit v1.2.3