rust - 如何从函数更改实例?
问题描述
这是我的代码
struct AA{
size:i8
}
impl AA{
pub fn create()->Self{
Self { size: 10 }
}
pub fn world(mut self)->Self{
self.size+=2;
self
}
pub fn say(self){
println!("{}",self.size);
}
}
//cannot move out of `*aa` which is behind a mutable reference
fn hello(aa: &mut AA){//this function will make a change
aa.world();// <-- need to call world() from here
}
fn main() {
let mut a=AA::create();
hello(&mut a);
a.say();// <-- need to call say() from here after hello() does the change
//AA::create().world().say(); <-- this works
}
如何在 rust 中实现以下目标?
从主(),
- 创建实例
- 将实例传递给 world() 以便它可以更改实例
- 更改发生后,从 main 调用实例的 say()
解决方案
这种替代方案对您有用吗?
struct AA {
size: i8,
}
impl AA {
pub fn create() -> Self {
Self { size: 10 }
}
pub fn world(mut self) -> Self {
self.size += 2;
self
}
pub fn say(self) {
println!("{}", self.size);
}
}
fn hello(aa: AA) -> AA {
aa.world()
}
fn main() {
let mut a = AA::create();
a = hello(a);
a.say();
}
注意 world 返回一个 Self 类型, hello 也返回AA
。通过这种方式a
,hello()
我们使用它并返回它的新版本,而不是传递一个可变引用。
另一种选择是两者都world
接受say
引用self
而不是使用它们,在这种情况下,代码段将是:
pub fn world(&self) -> Self {
AA {
size: self.size + 2,
}
}
pub fn say(&self) {
println!("{}", self.size);
}
推荐阅读
- linux - bash 问题中的 Sed 正则表达式
- android - 禁用 Flutter Hero 反向动画
- ms-word - Office 的 Javascript API - 带有锚点的内联图像
- amazon-web-services - 无法从 ec2 linux 实例连接到特定域
- java - 与 spring 数据 jdbc 一起使用时,PagingAndSortingRepository 方法会引发错误
- python - 可以从现有日期时间实例创建的自定义日期时间子类?
- java - 使用三刺的处理方法
- corda - 如何限制观察者节点进行任何交易
- php - 将 php5 升级到 php7 后 AJAX 无法正常工作
- firebase - Angular CLI 支持子域反向代理