summaryrefslogtreecommitdiff
path: root/rust-book/lifetimes/src/main.rs
blob: 87b6ce6a76ad31703dd59c20bc28e0d6a426032f (plain) (blame)
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
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
    // what this is doing is basically tagging x and y and the
    // result with the same 'a, telling rust not to let any
    // of them expire before the others; that way nothing
    // will go out of scope prematurely and the result will
    // always have a non-null reference

    // basically, 'a gives all three values the same lifetime.
    // so long as they're all alive at the same time, there are
    // no reference errors
    
    // note that the lifetime selected for the result is 
    // equal to the smaller of the lifetimes of the 
    // parameters

    if x.len() > y.len() {
        x
    }
    else {
        y
    }
}

struct ImportantExcerpt<'a> {
    part: &'a str,
}

fn main() {
    let string1 = String::from("abcd");
    {
    let string2 = "xyz";

    let result = longest(string1.as_str(), string2);
    //dbg!(result);
    }

    let script = String::from("Before time began, there was the cube. We know not where it comes from.");
    let first_sentence = script.split('.')
        .next()
        .expect("Could not find a '.'");
    let i = ImportantExcerpt { part: first_sentence };
    dbg!(i.part);
}