【发布时间】:2018-10-12 11:00:19
【问题描述】:
这是拼凑在一起的,以说明我在使用 switch 函数时遇到的问题。无休止地打印“左”“右”没有问题。
switch 的重点是将枚举的值交换为另一个。此解决方案不起作用,因为大概switch 将t 移动到自身中,因此它不再可用。使用可变引用会导致许多其他问题,例如生命周期和不匹配的类型。该文档有说明如何使用结构而不是枚举来执行此操作。编译器建议在枚举中实现Copy 和Clone,但这没有任何用处。
这种方法应该如何在 Rust 中实现?
fn main() {
let mut t = Dir::Left;
loop {
match &t {
&Dir::Left => println!("Left"),
&Dir::Right => println!("Right"),
}
t.switch();
}
}
enum Dir {
Left,
Right,
}
impl Dir {
//this function is the problem here
fn switch(mut self) {
match self {
Dir::Left => self = Dir::Right,
Dir::Right => self = Dir::Left,
};
}
}
我当然可以这样做
t = t.switch();
和
fn switch(mut self) -> Self {
match self {
Dir::Left => return Dir::Right,
Dir::Right => return Dir::Left,
};
}
但我觉得这将是一个比较笨拙的解决方案,如果可能的话,我想避免它。
【问题讨论】: