jeje
jeje

Reputation: 3221

How to tell the compiler a lifetime is no longer valid?

While I understand why the compiler doesn't like the last statement in this code:


struct Person<'a> {
    name: &'a str,
}
impl<'a> Person<'a> {
    pub fn replace_name(&mut self, newname: &'a str) {
        self.name = newname;
    }
}

#[test]
fn test_person() {
    let firstname = "John".to_string();
    let mut p = Person { name: &firstname };
    assert_eq!(p.name, "John");

    {
        let newname = "Bob".to_string();
        p.replace_name(&newname);
        assert_eq!(p.name, "Bob");
        p.replace_name(&firstname);
    }
    // This will fail because the lifetime of newname is shorter than p:
    //assert_eq!(p.name, "John");
}

How can I tell it that it's OK because I replaced the newname with firstname?

Upvotes: 1

Views: 44

Answers (0)

Related Questions