这是拼凑在一起来说明我在switch函数中遇到的问题。我无休止地打印“左”“右”没有问题。
重点switch是将 enum 的值交换到另一个值。此解决方案不起作用,因为大概是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,
        };
    }
}
Run Code Online (Sandbox Code Playgroud)
我当然可以这样做
t = t.switch();
Run Code Online (Sandbox Code Playgroud)
和
fn switch(mut self) -> Self {
    match self {
        Dir::Left  => return Dir::Right,
        Dir::Right => return Dir::Left,
    };
}
Run Code Online (Sandbox Code Playgroud)
但我觉得这将是一个比较笨拙的解决方案,如果可能的话,我想避免它。
Fre*_*ios 11
您的方法使用您的数据而不是借用它。如果你借用它,它工作正常:
impl Dir {
    fn switch(&mut self) {
        *self = match *self {
            Dir::Left => Dir::Right,
            Dir::Right => Dir::Left,
        };
    }
}
Run Code Online (Sandbox Code Playgroud)
        |   归档时间:  |  
           
  |  
        
|   查看次数:  |  
           1108 次  |  
        
|   最近记录:  |