Rust 如何匹配包含&;的元组;mut enum并在一个匹配臂中使用enum,在另一个匹配臂中使用递归调用?

Rust 如何匹配包含&;的元组;mut enum并在一个匹配臂中使用enum,在另一个匹配臂中使用递归调用?,rust,pattern-matching,borrow-checker,Rust,Pattern Matching,Borrow Checker,如何编译下面的代码?它看起来非常安全,但我无法让编译器相信它是安全的 与*self匹配的版本会给出错误: 错误[E0507]:无法移出借用的内容 -->src/main.rs:8:16 | 8 |匹配(*self,y){ |^^^^无法移出借用的内容 与self匹配的版本给出: 错误[E0382]:使用移动值:`*self` -->src/main.rs:17:26 | 8 |匹配(自我,y){ |----值移到了这里 ... 17 |(*a*b,self) |^^^^^移动后此处使用的值 |

如何编译下面的代码?它看起来非常安全,但我无法让编译器相信它是安全的

*self
匹配的版本会给出错误:

错误[E0507]:无法移出借用的内容
-->src/main.rs:8:16
|
8 |匹配(*self,y){
|^^^^无法移出借用的内容
self
匹配的版本给出:

错误[E0382]:使用移动值:`*self`
-->src/main.rs:17:26
|
8 |匹配(自我,y){
|----值移到了这里
...
17 |(*a*b,self)
|^^^^^移动后此处使用的值
|

=注意:之所以发生移动,是因为'self'具有类型`&'a mut Foo,这似乎是编译的,但它非常难看。有什么方法可以简化它吗

enum Foo<'a> {
    Foo1(Option<&'a mut Foo<'a>>),
    Foo2(i16),
}

impl<'a> Foo<'a> {
    fn bar(&'a mut self, y: i16) -> (i16, &'a mut Foo<'a>) {
        match (&mut *self, y) {
            (Foo::Foo1(Some(ref mut a)), b) if (b == 5) => {
                return a.bar(y)
            },

            (self2, c) => {
                let n = match (&mut *self2 , c) {
                    (Foo::Foo2(ref mut a), b) if (b == 5) => {
                        print!("is five");
                        *a = (b + 42) as i16;

                        *a * b
                    },

                    ref mut x => {
                        print!("is not five!");
                        y
                    }
                };

                return (n, self2)
            }
        }
    }
}

enum Foo Foo(i16,&'a mut Foo,返回
self
似乎没有任何作用。但它确实起作用,因为当使用
Foo::Foo1(Foo::Foo1(Foo::Foo1(Foo::Foo2(5))
调用它时,返回的引用是指向
Foo:Foo2(5)
,而不是传入的原始引用。重点是在数据结构中搜索该元素。调整第二和第三个问题中的解决方案,在第一个问题中提前返回,在这里不起作用:
不能借用*self作为一次可更改的元素。
我相信您的问题已经得到了回答根据的答案。如果您不同意,请您的问题解释差异。否则,我们可以将此问题标记为已回答。
(ref mut f @ Foo::Foo1, b) if (b == 5) => {
    print!("is five");
    f.0 = b + 42;
    (b, f)
} 
enum Foo<'a> {
    Foo1(Option<&'a mut Foo<'a>>),
    Foo2(i16),
}

impl<'a> Foo<'a> {
    fn bar(&'a mut self, y: i16) -> (i16, &'a mut Foo<'a>) {
        match (&mut *self, y) {
            (Foo::Foo1(Some(ref mut a)), b) if (b == 5) => {
                return a.bar(y)
            },

            (self2, c) => {
                let n = match (&mut *self2 , c) {
                    (Foo::Foo2(ref mut a), b) if (b == 5) => {
                        print!("is five");
                        *a = (b + 42) as i16;

                        *a * b
                    },

                    ref mut x => {
                        print!("is not five!");
                        y
                    }
                };

                return (n, self2)
            }
        }
    }
}