在枚举方法中改变自我

Rit*_*lko 5 enums self rust

这是拼凑在一起来说明我在switch函数中遇到的问题。我无休止地打印“左”“右”没有问题。

重点switch是将 enum 的值交换到另一个值。此解决方案不起作用,因为大概是switch移动t到自身中,因此不再可用。使用可变引用会导致一系列其他问题,例如生命周期和不匹配的类型。该文档有说明如何使用结构执行此操作,但没有说明。编译器建议实现CopyClone枚举,但这没有任何用处。

这种类型的方法应该如何在 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)

  • @Ritielko 您需要(重新)阅读 Rust 书中的基础知识。在 Rust 中,所有东西都归一个作用域所有,您可以将它们交给另一个作用域,也可以借给它们(*即*它们是借来的),就像您的个人物品一样:您可以将它们交给某人或借给它们给一个朋友。`&` 表示不转让所有权。 (2认同)