rust - 将元素添加到 Rust 中的可变向量列表
问题描述
我是一个新手学习 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
。有没有更惯用的方法?当我尝试让事情变得可变时,我得到了一大堆错误,我不知道如何修复......
解决方案
你必须可变地借用self
:
impl <'a> FriendsList<'a> {
// [...]
fn add_new_friend(&mut self, friend: Friend<'a>) {
self.friends.push(friend)
}
}
推荐阅读
- java - 如何更改 NetBeans 中的默认 Java FX 控制器模板?
- android - org.parceler.Parcel:当构造函数包含布尔字段时,没有找到构造函数参数的对应属性
- string - 通过移动语义将所有可变参数转换为单个 std::string
- teradata - REGEXP REPLACE teradata 以消除出现在地址字段中的数字单词
- python - 基于其他列在数据框中标记文本和计数
- apache-spark - 获取:导入 Spark 模块时出错:没有名为“pyspark.streaming.kafka”的模块
- postgresql - pg_dump 创建了很多 pg_catalog 语句
- javascript - ajax后在当前页面找不到节点
- angular - 无法在 ngOnInit() 中测试订阅
- abap - 获取第一行非索引内部表