gpt4 book ai didi

rust - Rust 生命周期说明符的语法

转载 作者:行者123 更新时间:2023-11-29 08:14:56 25 4
gpt4 key购买 nike

我需要帮助来理解生命周期说明符。我想我明白了生命周期的概念。我看了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);
}

最佳答案

我不确定您的确切问题是什么,所以我想您希望编译该代码。检查这个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);
}

关于rust - Rust 生命周期说明符的语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26705277/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com