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);
}
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 justUser
.