我在尝试解决this question的不同方法时遇到了这个问题。
我正在尝试定义一个特征,该特征通过引用接受一个参数,并返回Self
,如下所示:
struct X {}
trait CopyFrom {
fn copy_from(&x: X) -> Self;
}
我得到的错误是:
error[E0642]: patterns aren't allowed in functions without bodies
--> src/main.rs:5:18
|
5 | fn copy_from(&x: X) -> Self;
| ^^ pattern not allowed in function without body
如果我按值取
x
,它可以很好地编译(但这会消耗我不想要的参数)。Rust引用说明是这样的:
The kinds of patterns for parameters is limited to one of the following:
- IDENTIFIER
- mut IDENTIFIER
- _
- & IDENTIFIER
- && IDENTIFIER
Beginning in the 2018 edition, function or method parameter patterns are no longer optional. Also, all irrefutable patterns are allowed as long as there is a body. Without a body, the limitations listed above are still in effect.
我找不到其他可以解释为什么我无法定义通过引用接受参数的特征函数的东西。
最佳答案
您在这里使用了错误的语法-&x: X
是一个reference pattern,它取消引用了X
类型的参数;换一种说法,
fn f(&x: X) {
// ...
}
相当于
fn f(x: X) {
let &x = x;
}
反过来,这意味着
fn f(x: X) {
let x = *x;
}
相反,您想使参数本身成为引用:
fn f(x: &X) { // take argument by reference
// ...
}
关于rust - 如何定义通过引用接受参数的特征函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61706320/