gpt4 book ai didi

rust - 如何在不复制一对借用值的情况下对它们使用匹配?

转载 作者:行者123 更新时间:2023-11-29 08:23:04 25 4
gpt4 key购买 nike

我将我的问题简化为以下代码:

enum E {
E1,
}

fn f(e1: &E, e2: &E) {
match *e1 {
E::E1 => (),
}
match (*e1, *e2) {
(E::E1, E::E1) => (),
}
}

fn main() {}

第一次匹配成功,第二次编译失败:

error[E0507]: cannot move out of borrowed content
--> src/main.rs:9:12
|
9 | match (*e1, *e2) {
| ^^^ cannot move out of borrowed content

error[E0507]: cannot move out of borrowed content
--> src/main.rs:9:17
|
9 | match (*e1, *e2) {
| ^^^ cannot move out of borrowed content

这似乎是因为我正在构造一对借来的东西,而 Rust 试图将 e1e2 移入其中。我发现如果我在枚举前加上“#[derive(Copy, Clone)]”,我的代码就会编译。

最佳答案

您可以通过从变量中删除取消引用运算符来匹配两个引用的元组:

enum E {
E1,
}

fn f(e1: &E, e2: &E) {
match *e1 {
E::E1 => (),
}
match (e1, e2) {
(&E::E1, &E::E1) => (),
}
}

关于rust - 如何在不复制一对借用值的情况下对它们使用匹配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28530338/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com