Need help understanding lifetimes

⚓ Rust    📅 2026-02-19    👤 surdeus    👁️ 1      

surdeus

Why below code compiles :-

fn strtok<'a>(s: &'a str, delimiter: char) -> &'a str {
    &s[0..5]
}

fn main() {
    let mut x = "hello world";
    let hello = strtok(&x, ' ');
    //println!("{}", hello);
    let mut z = &mut x;
    println!("{}", hello);
}

In the snippet borrow of x has same lifetime as hello which will last till last usage. And we are trying to borrow x mutably in between which shouldn't compile.

5 posts - 4 participants

Read full topic

🏷️ Rust_feed