-
Notifications
You must be signed in to change notification settings - Fork 2
/
memory_management.rs
68 lines (60 loc) · 1.95 KB
/
memory_management.rs
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
pub fn run() {
owner_variable();
borrow_variable();
reference_dereference();
}
/**
One of the best feature of [rust] by design is the memory management, and how protect our programs in compilation time.
Every variable allocated in heap memory, can only have one owner. So in case we decide to transfer the content of one
variable to another, the old one cannot be used anymore, and it wont compile if you want to use it.
*/
fn owner_variable() {
let variable = String::from("Memory management:Transferring");
let transfer_variable = variable;
// println!("{}", variable);//It wont compile
println!("{}", transfer_variable);
}
/**
One way that we can assign the content of one variable into another, is not doing a copy, but passing
a reference(pointer) [&] just like in c, c++.
Once we do that we can continue using the old variable since what we made with the new allocation is pass a reference.
*/
fn borrow_variable() {
let variable = String::from("Memory management:Borrowing");
let new_variable = &variable;
println!("{}", variable);
// println!("{}", variable.push_str("Change value"));//It wont compile
println!("{}", new_variable);
}
/**
When we use [&] we are creating a reference [pointer] of a variable.
And when we use [*] we are de-referencing a reference.
*/
fn reference_dereference() {
let x = 5;
let y = &x; //set y to a reference to x
assert_eq!(5, x);
let i = *y;
assert_eq!(5, i); // dereference y
}
fn extend_lifetime() {
let x = "hello world".to_string();
let y = &x;
foo(y)
}
/// [z] is marked with the explicit lifetime, and is failing since [d] not living long enough, since once
/// is copy, is destroyed.
fn foo<'a>(x: &'a String) {
println!("${}", x);
let d = "hello again".to_string();
// let z: &'a String = &d;
// println!("${}", z);
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn extend_lifetime_test() {
extend_lifetime()
}
}