【发布时间】:2018-07-13 16:33:05
【问题描述】:
如何编译下面的代码?它看起来非常安全,但无法说服编译器。
匹配*self的版本给出错误:cannot move out of borrowed content在匹配的行
匹配self的版本给出:use of moved value: *self
enum Foo {
Foo1(u32),
Foo2(i16),
}
impl Foo {
fn bar(&mut self, y: u32) -> (u32, &mut Foo) {
match (*self, y) {
(Foo::Foo1(ref mut a), b) if (b == 5) => {
print!("is five");
*a = b + 42;
(b, self)
}
(Foo::Foo2(ref mut a), b) if (b == 5) => {
print!("is five");
*a = (b + 42) as i16;
(*a * b, self)
}
_ => {
print!("is not five!");
(y, self)
}
}
}
}
我觉得我需要一个如下所示的匹配臂,但它似乎不是有效的语法:
(ref mut f @ Foo::Foo1, b) if (b == 5) => {
print!("is five");
f.0 = b + 42;
(b, f)
}
error[E0532]: expected unit struct/variant or constant, found tuple variant `Foo::Foo1`
--> src/main.rs:24:30
|
24 | (ref mut f @ Foo::Foo1, b) if (b == 5) => {
| ^^^^^^^^^ not a unit struct/variant or constant
【问题讨论】:
-
“看起来非常安全”,我的 C 代码看起来也非常安全,但 rust 不是关于“似乎”而是“是”
-
我现在正在阅读链接的问题,但您的解决方案仍然给我
use of moved value: *self -
请注意,我也在尝试返回 self,发生错误的地方
标签: rust pattern-matching borrow-checker