summaryrefslogtreecommitdiff
path: root/rust/refs_and_borrows/src/main.rs
blob: 212372bce310c6e31050086a158b78c3111b03fc (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
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
fn main() {
    let m1 = String::from("Hello");
    let m2 = String::from("world");

    // Borrow m1 and m2 references to greet(), instead of passing ownership
    greet(&m1, &m2);
    let s = format!("{} {}", m1, m2);
    println!("{s}");

//    fing_it();
//    aliasing_bonanza();
//    mutable_bonanza();
    flow_me();
}

// g1 is a reference that points to m1 on the stack, and m1 is a String
// containing a box, pointing to "Hello" string on the heap.
fn greet(g1: &String, g2: &String) -> () {
    println!("Greet: {}, {}", *g1, *g2);
}

fn fing_it() -> () {
    let mut x: Box<i32> = Box::new(1);
    let _a:i32 = *x;
    *x += 1;

    let ref1: Box<i32> = Box::new(-5);

    println!("This is sparta: {}", i32::abs(*ref1));
}

/*
fn aliasing_bonanza() -> () {
    let mut v: Vec<i32> = vec![10, 20, 30];
    let num: &i32 = &v[2];
    v.push(40);

    println!("{:?}", *num)
}
*/
fn mutable_bonanza() -> () {
    let mut v: Vec<i32> = vec![10, 20, 30];

    // let mut <var>  makes the VAR <var> mutable, i.e. it can be reassigned
    // let <var>:&mut i32 = &mut foo creates an IMMUTABLE <var> that points to a
    // mutable memory

    let num: &mut i32 = &mut v[2];
    let num2: &i32 = num;

    println!("Index 2 == {}", *num2);
}

// Yes, moving { to the next line on purpose
fn flow_me(strings: &Vec<String>, default: &String) -> &String
{
    if strings.len() > 0 {
        &strings[0]
    } else {
        default
    }
}