summaryrefslogtreecommitdiff
path: root/rust/partial_move.rs
diff options
context:
space:
mode:
authorCarlos Maiolino <[email protected]>2025-07-10 22:24:20 +0200
committerCarlos Maiolino <[email protected]>2025-07-10 22:24:20 +0200
commit869e68986aa8f69af6e7842260a68d1e5c6f796f (patch)
tree63b6b5ffc3d19414233d4629a533c0d9bf3cbf72 /rust/partial_move.rs
parent20834dcc57537cd95260a4a22f5d91a027adfd35 (diff)
Add a bunch of code
Signed-off-by: Carlos Maiolino <[email protected]>
Diffstat (limited to 'rust/partial_move.rs')
-rw-r--r--rust/partial_move.rs49
1 files changed, 49 insertions, 0 deletions
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<u8>,
+ }
+
+ 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);
+}