首页 > 解决方案 > 将元素添加到 Rust 中的可变向量列表

问题描述

这是一个游乐场的链接:https ://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=1e82dcd3d4b7d8af89c5c00597d2d938

我是一个新手学习 rust 并试图简单地更新结构上的可变向量。

struct Friend<'a> {
    name: &'a str
}

impl <'a> Friend<'a> {
    fn new(name: &'a str) ->  Self { Self { name } }    
}


struct FriendsList<'a> {
    name: &'a str,
    friends: Vec<Friend<'a>>
}

impl <'a> FriendsList<'a> {
    fn new(name: &'a str, friends: Vec<Friend<'a>>) -> Self { Self { name, friends } }
    fn add_new_friend(&self, friend: Friend) {
        // how to make this work?
        todo!()
        // self.friends.push(friend)
    }
}

fn main() {
    let friends_list = FriendsList::new("George",
        vec![
            Friend::new("bob"), 
            Friend::new("bobby"), 
            Friend::new("bobbo")
        ]
    );
}

具体来说,我该如何使这种fn add_new_friend(&self, friend: Friend)方法起作用?也就是说,将一个新元素推送到结构friends上的字段FriendsList。有没有更惯用的方法?当我尝试让事情变得可变时,我得到了一大堆错误,我不知道如何修复......

标签: rust

解决方案


你必须可变地借用self

impl <'a> FriendsList<'a> {
    // [...]

    fn add_new_friend(&mut self, friend: Friend<'a>) {
        self.friends.push(friend)
    }
}

推荐阅读