gpt4 book ai didi

rust - 为什么 Option 在匹配模式中失去可变性?

转载 作者:行者123 更新时间:2023-12-03 11:25:18 24 4
gpt4 key购买 nike

我要换 my_id ,仅当存在时,为另一个值:

fn read(id: &mut i32) {
*id = 42;
}

struct S {
my_id: Option<i32>,
}

impl S {
fn run(&mut self) {
match self.my_id {
Some(mut id) => read(&mut id),
_ => (),
}
}
}

fn main() {
let mut s = S { my_id: 0.into() };

s.run();

println!("{:?}", s.my_id);
}
playground
此代码打印 Some(0) ,这意味着替换失败,但我不明白为什么。我是否因为模式匹配而失去了可变性?

最佳答案

Shepmaster's answermcarton's answer很好地解释了您的 i32正在被复制而不是在模式匹配中被引用。
我想补充一点,ref关键字专门用于处理这样的情况,在这种情况下,您需要引用而不是模式匹配中的副本:

fn read(id: &mut i32) {
*id = 42;
}

struct S {
my_id: Option<i32>,
}

impl S {
fn run(&mut self) {
match self.my_id {
// `ref` keyword added here
Some(ref mut id) => read(id),
_ => (),
}
}
}

fn main() {
let mut s = S { my_id: 0.into() };
s.run();
println!("{:?}", s.my_id); // prints "Some(42)"
}
playground
也可以看看:
  • Was Rust's ref keyword avoidable?
  • How can the ref keyword be avoided when pattern matching in a function taking &self or &mut self?
  • Why is `ref` used instead of an asterisk in pattern matching?
  • 关于rust - 为什么 Option<i32> 在匹配模式中失去可变性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62517695/

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