LoginSignup
5
2

More than 5 years have passed since last update.

Rust で mut self と self の互換性

Last updated at Posted at 2018-01-08

以下のようなtraitがあったとき、

trait
trait BarTrait {
    fn bar(self, x: i32);
}

以下のように、selfや他の引数にmutを付けてもimplできる(問題なくコンパイル可能)

impl
struct Foo {
    x: i32,
}

impl BarTrait for Foo {
    // selfとxに、それぞれBarTraitの定義にはなかったmutが付いている
    fn bar(mut self, mut x: i32) {
        self.x += 1;
        x += 1;
        println!("bar for foo: {} {}", self.x, x);
    }
}

mutの有無は関数内部の実装の問題で、外から見たIFには影響しない。
(C++でも、メソッドの宣言と定義で値引数のconstの有無が異なったり、override時に値引数のconstの有無が異なっても問題ない(ポインタ引数での向き先のconstの有無に関してはもちろん駄目))

さらに、以下のようにmut付きで定義したメソッドのドキュメントでは、自動的にmutが省かれる:

impl Foo {
    /// foo
    pub fn foo(mut self, mut x: i32) {
        self.x = 0;
        x = 1;
        println!("{} {}", self.x, x);
    }
}
ドキュメントを生成
cargo doc
foo.png

↑生成されたドキュメント。selfとxにmutが付いていない。

補足

実際、たとえmutを付けずに実装しても、以下のようにすればいくらでも後からmutに変更可能。

    fn bar(self, x: i32) {
        let mut mself = self;
        let mut x = x;
        ...

引数のmutの有無に本質的な違いはないことが分かる。
(もちろん、&self&mut selfだとこうはいかない)

5
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
2