Rust生存期说明符的语法

时间:2014-11-02 22:37:01

标签: rust lifetime

我需要帮助了解终身说明符。我想我得到了生命的概念。我看了Memory, Ownership and Lifetimes。我只是想如果我可以通过这个小example来解决它,它可能会帮助我解决生命周期的语法问题。到目前为止,我发现一个令人困惑的话题。

use std::collections::HashMap;

fn main() {
    pub struct User<'a> {
        pub name: & 'a str
    }

    impl <'a>User<'a> {
        pub fn new(uname: & 'a str, pwd: & 'a str) -> User {
            User{name: uname}
        }
    }

    pub struct ChatRoom<'a> {
        pub name: & 'a str,
        pub users: HashMap<& 'a str, User>  
    }


    impl <'a>ChatRoom<'a> {
        pub fn new(name: &str) -> ChatRoom {
            let users = HashMap::new();
            ChatRoom {name: name, users: users}
        }

        pub fn join(&mut self, user: User) {
            self.users.insert(user.name, user);
        }
    }

    let mut room = ChatRoom::new("Test");
    let user = User::new("bender","123");
    room.join(user);
}

1 个答案:

答案 0 :(得分:3)

我不确定你的确切问题是什么,所以我想你想要编译代码。请检查此playground

请注意,生命周期参数是该类型的一部分,因此您希望User<'a>不仅仅是User

use std::collections::HashMap;

fn main() {
    struct User<'a> {
        name: &'a str,
    }

    impl<'a> User<'a> {
        fn new(uname: &'a str, pwd: &'a str) -> User<'a> {
            User { name: uname }
        }
    }

    struct ChatRoom<'a> {
        name: &'a str,
        users: HashMap<&'a str, User<'a>>,
    }

    impl<'a> ChatRoom<'a> {
        fn new(name: &str) -> ChatRoom {
            let users = HashMap::new();
            ChatRoom {
                name: name,
                users: users,
            }
        }

        fn join(&mut self, user: User<'a>) {
            self.users.insert(user.name, user);
        }
    }

    let mut room = ChatRoom::new("Test");
    let user = User::new("bender", "123");
    room.join(user);
}