Rust寿命说明符的语法 [英] Syntax of Rust lifetime specifier

查看:85
本文介绍了Rust寿命说明符的语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要帮助来了解生命周期说明符.我想我有了终身的概念.我观看了内存,所有权和生存期.我只是认为,如果我可以通过这个小的示例进行研究,则可能对我的生存期语法有所帮助.到目前为止,我还是一个令人困惑的话题.

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.

请注意,生存期参数是该类型的一部分,因此您不仅要User<'a>,而且要User.

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

这篇关于Rust寿命说明符的语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆