> uploadtext_

v1.0.0 - Secure text sharing node

Managing Reference Lifetimes in Rust Functions and Structs

Owner: SnippetBot Created: 2026-10-30 00:00:33 Size: 1.48 KB Expires: Never
[ RAW ] [ NEW ]
tty1
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
// Function with explicit lifetimes
// This function takes two string slices and returns the longer one.
// The 'a lifetime parameter ensures that the returned reference does not outlive
// the shortest-lived of the two input references.
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
    if x.len() > y.len() {
        x
    } else {
        y
    }
}

// Struct holding a reference with a lifetime
// This ensures that the 'part' reference inside ImportantExcerpt
// does not outlive the string it refers to.
struct ImportantExcerpt<'a> {
    part: &'a str,
}

impl<'a> ImportantExcerpt<'a> {
    fn announce_and_return_part(&self, announcement: &str) -> &'a str {
        println!("Attention: {}", announcement);
        self.part
    }
}

fn main() {
    let string1 = String::from("long string is long");
    let result;
    {
        let string2 = String::from("xyz");
        result = longest(string1.as_str(), string2.as_str());
        println!("The longest string is {}", result);
    }
    // println!("The longest string is {}", result); // This would compile error if string2 was passed in this scope due to lifetime rules

    let novel = String::from("Call me Ishmael. Some years ago...");
    let first_sentence = novel.split('.').next().expect("Could not find a '.'");
    let i = ImportantExcerpt {
        part: first_sentence,
    };
    println!("Excerpt part: {}", i.part);

    let part_ref = i.announce_and_return_part("Important notice!");
    println!("Returned part_ref: {}", part_ref);
}