summaryrefslogtreecommitdiff
path: root/rust/owner_ex.rs
blob: f76a783e5c70ec5c4be184a77a01447e302f024a (plain)
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
fn main() {

    // This is interesting...
    // &str annotate we are using a string literal, not creating
    // a string at run time.
    // It means the size of the tuple is known at compilation time.
    let x: (i32, i32, (), &str) = (1, 2, (), "hello");

    // Because we know the tuple size at compilation time, (and likely
    // because it's allocated on the stack, we can simply copy it here.
    let y: (i32, i32, (), &str) = x;

    println!("{:?}, {:?}", x, y);

    // s oritinally immutable
    let s: String = String::from("hello, ");

    // Transferring ownership can be done to a mutable variable
    let mut s1 = s;

    s1.push_str("world");

    println!("{}", s1);

    // x now is a pointer to the heap memory
    let x: Box<i32> = Box::new(5);

    // y is also a pointer
    let mut y: Box<i32> = Box::new(1);

    // Dereferencing Y address
    *y = 4;

    assert_eq!(*x, 5);
}