rust - 如何定义通过引用接受参数的特征函数

标签 rust

我在尝试解决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/

相关文章:

rust - 使用 impl fmt::Display 将枚举转换为字符串

macros - 匹配下划线而不是宏中的标识

loops - 如何访问 BufReader 两次?

reference - 迭代器通过引用返回项目,生命周期问题

rust - 如何让调用者看到方法的特征实现?

rust - 有没有一种方法可以在构造函数中使用锁定的标准输入和输出,使其与您正在构造的结构一样长?

git - 如何将常量映射到自定义字符串

rust - 当索引检查越界时分配返回值

asynchronous - 如何将向量作为异步流处理?

macros - 如何获取宏重复单元素的索引