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/partial_move.rs | 49 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 rust/partial_move.rs (limited to 'rust/partial_move.rs') diff --git a/rust/partial_move.rs b/rust/partial_move.rs new file mode 100644 index 0000000..84fb163 --- /dev/null +++ b/rust/partial_move.rs @@ -0,0 +1,49 @@ +fn main() { + #[derive(Debug)] + struct Person { + name: String, + age: Box, + } + + let alice: Person = Person { + name: String::from("Alice"), + age: Box::new(20), + }; + + println!("{} {}", alice.name, *alice.age); + + // Destructure the fields of the variable 'alice' + // + // Now we've got two new variables, name and age. + // + // Notice the 'ref' keyword here, meaning 'age', meaning + // 'age' is just a reference to the data. + // 'name' though, will be moved here, and this 'name' var + // will be the new owner of this data. + // + let Person {name, ref age} = alice; + + // From now on, 'alice' Struct is not anymore, it has no + // ownership of its data. + // Its data has been dismembered and it's now owned by + // 'name' and 'age' + println!("Name: {} - Age: {}", name, *age); + + // Destructuring tuples + + // Tuple containing two strings + let t: (String, String) = ((String::from("Ronaldo")), (String::from("Brilha Muito"))); + + let s: String = t.0; + + println!("{} {}", s, t.1); + + // I can't access t.0 directly anymore as the string's ownership has been moved to 's' + // println!("{}", t.0); // Kaboom + + let t2: (String, String) = ((String::from("Foo")), (String::from("Bar"))); + + let (new_t1, new_t2): (String, String) = t2.clone(); + + println!("STR1: {} STR2: {}", new_t1, new_t2); +} -- cgit v1.2.3