LoginSignup
2
1

More than 3 years have passed since last update.

Rustで"this is an associated function, not a method"のエラーが出たのでメソッドと関連関数について調べてみた

Posted at

エラーに遭遇

今日もRustをダラダラ書いていると,

error[E0599]: no method named `listen_and_serve` found for struct `servers::Server` in the current scope
  --> inferno-rtmp-engine/src/servers/tests.rs:6:12
   |
6  |     server.listen_and_serve();
   |     -------^^^^^^^^^^^^^^^^
   |     |      |
   |     |      this is an associated function, not a method
   |     help: use associated function syntax instead: `servers::Server::listen_and_serve`

というエラーに遭遇してしまいました。
this is an associated function, not a methodって,僕がいままでメソッドだと思っていたものはメソッドではなかったのでしょうか...

なので,Rustのメソッドとこのassociated functionについて少し詳しくなるために色々調べてみました。

Associated Function(関連関数)

この関連関数というのは,名前の通り型に関連付けられた関数のことらしいです。

struct Struct {
    field: i32
}

impl Struct {
    fn new() -> Struct {
        Struct {
            field: 0i32
        }
    }
}

fn main () {
    let _struct = Struct::new();
}

メソッド

メソッドは関数に似ていますが,構造体の文脈(?)で定義されており,最初の引数が必ずselfになるらしく,これはメソッドを呼び出している構造体のインスタンスを示しているらしいです。

#[derive(Debug)]
struct Rectangle {
    width: u32,
    height: u32,
}

impl Rectangle {
    fn area(&self) -> u32 {
        self.width * self.height
    }
}

fn main() {
    let rect1 = Rectangle { width: 30, height: 50 };

    println!(
        "The area of the rectangle is {} square pixels.",
        rect1.area()
    );
}

ぼんやりとわかったようなわからないような...

関連関数とメソッドの差

ドキュメントにはこう書かれています。

Associated functions whose first parameter is named self are called methods and may be invoked using the method call operator, for example, x.foo(), as well as the usual function call notation.

関連関数の最初の引数がselfのものはメソッドと呼ばれ,x.foo()のようにメソッド呼び出し構文で呼び出せるっていってますかね。

違いはほんとにこれだけなのでしょうか?
もう少し調べてみます。

好きな方を使ってもよさそう?

リンクをみていた感じでは,メソッド呼び出し構文を使いたい場合は関連関数の第一引数をselfにして利用できるみたいで,別に必要ないなら関連関数として使っちゃってもいいみたいな感じでしょうか。

おわり

Rustまだまだよくわからないことだらけですが,ひとつひとつ調べてがんばっていこうと思います!

参考リンク

https://doc.rust-lang.org/reference/items/associated-items.html
https://doc.rust-jp.rs/book/second-edition/ch05-03-method-syntax.html
https://www.reddit.com/r/rust/comments/ahqjyq/how_to_use_method_of_own_object/

2
1
2

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
2
1