2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Rust】メソッド、関連関数

2
Posted at

参考

メソッド

Rustのメソッドは、構造体に対して直接呼び出すことができる関数で、関数とは異なり、最初の引数は必ずselfになり、これはメソッドが呼び出されている構造体インスタンスを表します。

具体的には、以下のようにしてメソッドを定義できます。

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());
}

Rectangleの文脈内で関数を定義するには、implブロックを始めます。
それから、 area関数をimplの波括弧内に移動させ、引数をシグネチャ内と本体内の両方でselfに変えます。

この関数を呼び出すとき、rect1.area()というように構造体変数のインスタンス.メソッド名()の構文を使用します。

関連関数

また、implブロックの中では、self以外の引数を持つ関数を定義することもできます。

これらの関数は、構造体の文脈で直接アクセスできるため、関連関数 (associated functions) と呼ばれます。

関連関数を定義するには、implブロックの中で、selfを引数に取らない関数を定義します。

例えば、以下のようにして関連関数を定義することができます。

struct Rectangle {
    width: u32,
    height: u32,
}

impl Rectangle {
    fn new(width: u32, height: u32) -> Rectangle {
        Rectangle { width, height }
    }
}

fn main() {
    let rect1 = Rectangle::new(30, 50);
    println!("The area of the rectangle is {} square pixels.", rect1.area());
}

この例では、new関数を定義しています。
この関数は、implブロックの中にある構造体を新しく作成するための関数であり、selfという引数は必要ありません。

また、new関数を呼び出すときは、Rectangle::newのように、関連関数を呼び出すときは、構造体名の直前に::を使用します。

関連関数を定義するときには、その関数が特定の構造体に関連つけられているものであることを明示的に示す必要があります。

それが、例えば Rectangle::newのように、構造体の名前を一緒にして呼び出す理由です。

関連関数は、構造体のコンストラクタや、同じ構造体に関連する関数をまとめるのに便利です。
また、関連関数は、構造体を初期化する際に実行する手続きをカプセル化するために役立つことがあります。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?