Syntax of Rust lifetime specifier

风格不统一 提交于 2020-01-05 07:38:10

问题


I need help understanding lifetime specifiers. I think I get the concept of lifetimes. I watched Memory, Ownership and Lifetimes. I just think if I could work through this small example it might help me with the syntax of lifetimes. A topic I, to date, find confusing.

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:


I'm not sure what your exact question is, so I imagine you wanted that code to compile. Check this playground.

Notice that lifetime parameters are part of the type, so you want User<'a> not just 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);
}


来源:https://stackoverflow.com/questions/26705277/syntax-of-rust-lifetime-specifier

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!