简体   繁体   English

当 Trait 定义仅使用 self 时,为什么在 Trait 实现中允许 mut self?

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

I'm working on the traits2.rs exercise in rustlings and am confused on Rust's syntax for traits.我正在研究 rustlings 中的traits2.rs练习,并且对 Rust 的特征语法感到困惑。 I have the following working solution (that compiles and passes the test, I'm using Rust 1.50):我有以下工作解决方案(编译并通过测试,我使用的是 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
    }
}

However, I'm confused that, while the trait definition is fn append_bar(self) -> Self , my implementation for it is fn append_bar(mut self) -> Self , which has an additional mut on the signature.但是,我很困惑,虽然特征定义是fn append_bar(self) -> Self ,但我的实现是fn append_bar(mut self) -> Self ,它在签名上有一个额外的mut Why is this allowed?为什么允许这样做?

The Reference for associated functions says: 相关功能的参考说:

The identifier is the name of the function.标识符是 function 的名称。 The generics, parameter list, return type, and where clause of the associated function must be the same as the associated function declarations's.关联 function 的 generics、参数列表、返回类型和 where 子句必须与关联的 function 声明的相同。

Matching the parameter list means matching the number and types of parameters.匹配参数列表意味着匹配参数的数量和类型。 TheReference for functions explains the structure of a parameter: 函数参考解释了参数的结构:

FunctionParam: OuterAttribute* Pattern: Type函数参数:OuterAttribute* 模式:类型

Where Pattern in this case is an Identifier Pattern :在这种情况下Pattern是一个标识符 Pattern

IdentifierPattern: ref?标识符模式:参考? mut?哑巴? IDENTIFIER (@ Pattern )?标识符(@模式)?

This induces that mut is part of the pattern, not part of the type which is the reason why mut (unlike &mut ) is not part of the Signature at all, so thats why you are allowed to use it.这导致mut是模式的一部分,而不是类型的一部分,这就是为什么mut (不像&mut )根本不是签名的一部分,所以这就是为什么你被允许使用它的原因。

It's important to note here that mut self vs self is not the same as &self vs &mut self .需要注意的是, mut selfself&self&mut self不同。 As with other parameters, the mut in mut self is just an annotation on the binding of self , not the type.与其他参数一样, mut mut self中的 mut 只是self绑定的注释,而不是类型。

The caller does not need to know about it: you move the value one way or the other, so it's up to the callee if it needs to mutate it or not.调用者不需要知道它:你以一种或另一种方式移动值,所以它是否需要改变它取决于被调用者。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM