Weird lifetime coercion and variance

⚓ Rust    📅 2026-02-06    👤 surdeus    👁️ 12      

surdeus

Warning

This post was published 73 days ago. The information described in this article may have changed.

Hello everyone, can someone please explain how lifetime assignment exactly works here and how all this weirdness leads to the compile error that we have here...?

fn strtok<'a>(haystack: &'a mut &'a str, c: char) -> &'a str {
    if let Some(v) = haystack.find(c) {
        let first = &haystack[..v];
        *haystack = &haystack[(v + c.len_utf8())..];
        first
    } else {
        return *haystack;
    }
}

fn main() {
    let mut x = "hello world";
    // &'a mut &'a str -> what the function expects
    // &'x mut &'static str -> what I am providing
    let hello = strtok(&mut x, ' ');
    assert_eq!(hello, "hello");
    assert_eq!(x, "world");
}

4 posts - 4 participants

Read full topic

🏷️ Rust_feed