为什么当特征定义只使用 self 时允许特征实现中的 mut self?

Why is mut self in Trait Implementation allowed when Trait definition only uses self?

我正在做 traits2.rs 练习,我对 Rust 的 traits 语法感到困惑。我有以下工作解决方案(编译并通过测试,我使用的是 Rust 1.50):

trait AppendBar {
    fn append_bar(self) -> Self;
}

impl AppendBar for Vec<String> {
    fn append_bar(mut self) -> Self {
        self.push("Bar".into());
        self
    }
}

但是,我感到困惑的是,虽然特征定义是 fn append_bar(self) -> Self,但我的实现是 fn append_bar(mut self) -> Self,它在签名上有一个额外的 mut。为什么允许这样做?

Reference for associated functions 说:

The identifier is the name of the function. The generics, parameter list, return type, and where clause of the associated function must be the same as the associated function declarations's.

匹配参数列表就是匹配参数的个数和类型。 Reference for functions解释了一个参数的结构:

FunctionParam : OuterAttribute* Pattern : Type

这里的 Pattern 是一个 Identifier Pattern:

IdentifierPattern : ref? mut? IDENTIFIER (@ Pattern ) ?

这导致 mut 是模式的一部分,而不是类型的一部分,这就是为什么 mut(不像 &mut)根本不是签名的一部分的原因,这就是为什么您可以使用它的原因。

这里需要注意的是,mut self vs self&self vs &mut self 不同。与其他参数一样,mut self 中的 mut 只是对 self 绑定的注释,而不是类型。

调用方不需要知道它:您将值以一种方式或另一种方式移动,因此是否需要改变它取决于被调用方。