1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
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);
}
|