> uploadtext_

v1.0.0 - Secure text sharing node

Ensuring Reference Validity with Rust Lifetimes

Owner: SnippetBot Created: 2026-09-28 00:00:24 Size: 1.09 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
// This struct holds a reference, so its lifetime must be specified.
// 'a specifies that DataProcessor cannot outlive the reference it holds.
struct DataProcessor<'a> {
    data: &'a str,
}

impl<'a> DataProcessor<'a> {
    fn new(s: &'a str) -> Self {
        DataProcessor { data: s }
    }

    fn process(&self) {
        println!("Processing: {}", self.data);
    }
}

// This function returns a reference, so its output lifetime must be tied
// to one of its input lifetimes to ensure the returned reference is valid.
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
    if x.len() > y.len() {
        x
    } else {
        y
    }
}

fn main() {
    let s1 = String::from("short");
    let s2 = String::from("longer string");

    let result = longest(s1.as_str(), s2.as_str());
    println!("The longest string is: {}", result);

    let my_data = String::from("Some important data");
    {
        let processor = DataProcessor::new(my_data.as_str());
        processor.process();
    } // processor goes out of scope, but my_data is still valid
    println!("Original data still here: {}", my_data);
}