【发布时间】:2022-08-22 00:36:29
【问题描述】:
我有以下编译好的代码
#[derive(Debug, PartialEq, Clone)]
pub enum Expression {
Const(i32),
Neg(Box<Expression>),
Add(Box<Expression>, Box<Expression>),
}
fn simplify(expr: &Expression) -> Expression {
match expr {
Expression::Neg(x) => match **x {
Expression::Const(n) => Expression::Const(-n),
_ => expr.clone()
},
// GIVES ERROR
// Expression::Add(x, y) => match (**x, **y) {
// (Expression::Const(n), Expression::Const(m)) => Expression::Const(n + m),
// _ => expr.clone()
// },
Expression::Add(x, y) => match **x {
Expression::Const(n) => match **y {
Expression::Const(m) => Expression::Const(n + m),
_ => expr.clone()
}
_ => expr.clone()
}
_ => expr.clone()
}
}
但是,如果我用注释掉的版本替换 Expression::Add 手臂,我会收到以下编译器错误
error[E0507]: cannot move out of `**x` which is behind a shared reference
--> src/lib.rs:21:41
|
21 | Expression::Add(x, y) => match (**x, **y) {
| ^^^ move occurs because `**x` has type `Expression`, which does not implement the `Copy` trait
error[E0507]: cannot move out of `**y` which is behind a shared reference
--> src/lib.rs:21:46
|
21 | Expression::Add(x, y) => match (**x, **y) {
| ^^^ move occurs because `**y` has type `Expression`, which does not implement the `Copy` trait
For more information about this error, try `rustc --explain E0507`.
我们是否有理由匹配单独的**x,而不是像(**x, **y) 这样的元组?前者实际上是被转换还是隐藏了一些语法糖?有没有比使用两个嵌套匹配更简单的方法来编写这个Add arm?
编辑:我还看到有一个ref 关键字,即supposed to address 类似这样的东西,但是将我的元组匹配表达式更改为(ref **x, ref **y) 会产生语法错误(error: expected expression, found keyword ref)。
-
我不确定发生了什么,但
match (&**x, &**y)有效。 (而ref继续在匹配臂中进行变量声明。从语法上讲,您在错误的地方使用它。)
标签: rust match move-semantics