【问题标题】:Mutating self in enum method在枚举方法中改变自我
【发布时间】:2018-10-12 11:00:19
【问题描述】:

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

switch 的重点是将枚举的值交换为另一个。此解决方案不起作用,因为大概switcht 移动到自身中,因此它不再可用。使用可变引用会导致许多其他问题,例如生命周期和不匹配的类型。该文档有说明如何使用结构而不是枚举来执行此操作。编译器建议在枚举中实现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,
        };
    }
}

我当然可以这样做

t = t.switch();

fn switch(mut self) -> Self {
    match self {
        Dir::Left  => return Dir::Right,
        Dir::Right => return Dir::Left,
    };
}

但我觉得这将是一个比较笨拙的解决方案,如果可能的话,我想避免它。

【问题讨论】:

    标签: enums rust self


    【解决方案1】:

    您的方法使用您的数据而不是借用它。如果您借用它,它可以正常工作:

    impl Dir {
        fn switch(&mut self) {
            *self = match *self {
                Dir::Left => Dir::Right,
                Dir::Right => Dir::Left,
            };
        }
    }
    

    【讨论】:

    • 非常感谢。我没想过使用原始指针。为什么用* 借钱可以正常工作,但& 会造成一团糟?
    • @Ritielko 您需要(重新)阅读 Rust 书中的基础知识。在 Rust 中,所有东西都归一个作用域所有,你可以将它们交给另一个作用域,也可以借给它们(ie 它们是借来的),就像你的个人物品一样:你可以给它们给某人或借给朋友。 & 表示所有权未转让。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-08
    • 1970-01-01
    • 1970-01-01
    • 2012-12-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多