为什么在取消引用非元组时匹配在被取消引用的引用元组上不起作用? [英] Why does matching on a tuple of dereferenced references not work while dereferencing non-tuples does?

查看:94
本文介绍了为什么在取消引用非元组时匹配在被取消引用的引用元组上不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试对枚举的Vec进行排序.请忽略排序机制本身,这只是一个简化的示例.

I'm trying to sort a Vec of enums. Please ignore the sorting mechanism itself, this is just a stripped-down example.

use std::cmp::Ordering;

enum MyEnum {
    Option1,
    Option2,
}

fn main() {
    let mut my_list: Vec<MyEnum> = vec![MyEnum::Option1, MyEnum::Option2, MyEnum::Option1];

    // (1) - doesn't work
    my_list.sort_unstable_by(|a, b| match (*a, *b) {
        (MyEnum::Option1, MyEnum::Option1) => Ordering::Equal,
        (MyEnum::Option1, MyEnum::Option2) => Ordering::Less,
        _  => Ordering::Greater
    });
}

我收到以下错误:

error[E0507]: cannot move out of borrowed content
  --> src/main.rs:12:44
   |
12 |     my_list.sort_unstable_by(|a, b| match (*a, *b) {
   |                                            ^^ cannot move out of borrowed content

以下两个变体可以工作:

The following two variants work:

// (2)
my_list.sort_unstable_by(|a, _b| match *a {
    MyEnum::Option1 => Ordering::Less,
    MyEnum::Option2 => Ordering::Greater
});

// (3)
my_list.sort_unstable_by(|a, b| match (a, b) {
    (&MyEnum::Option1, &MyEnum::Option1) => Ordering::Equal,
    (&MyEnum::Option1, &MyEnum::Option2) => Ordering::Less,
    _  => Ordering::Greater
});

当我想匹配一个普通引用时,可以取消引用(变量2);为什么这在变体1的元组中不起作用?

When I want to match a plain reference, I can dereference it (variant 2); why doesn't this work inside the tuple in variant 1?

我理解3为何起作用,但是在理解1中确切发生的移动以及如何以不同的方式进行操作方面遇到困难.

I understand why 3 works, but struggle with understanding where exactly a move happens in 1 and how to do it differently.

推荐答案

确切发生移动的地方

where exactly a move happens

移动发生在编译器指向的位置-*a.您正在将a的内容移动到全新的元组中.您无法做到这一点,因此编译器会给出错误消息.

A move happens where the compiler is pointing — *a. You are moving the contents of a into a brand-new tuple. You can't do that, so the compiler gives an error.

在没有真正取消引用匹配变量的情况下取消引用"匹配变量的能力是编译器提供的某种语法优势,但是它非常有限.它不会查看"表达式,它只会查看某些选择的语法构造,并且会忽略它们.

The ability to "dereference" the matched variable without really dereferencing it is some syntactic goodness provided by the compiler, but it's very limited. It doesn't "see into" the expression, it only looks at some select syntax constructions and knows to ignore them.

可能可以增强编译器以查看这些情况,但是现在看来,成本/收益的权衡并不有利.

It's possible that the compiler could be enhanced to see these cases, but presumably the cost/benefit tradeoff isn't favorable at this point in time.

另请参阅:

  • Is there any difference between matching on a reference to a pattern or a dereferenced value?
  • How can I use match on a pair of borrowed values without copying them?
  • Matching on a reference to an enum

这篇关于为什么在取消引用非元组时匹配在被取消引用的引用元组上不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆