Rust:Rust の構造体と impl ブロック:メソッドと関連関数
Rust•メソッドと impl

Rust の構造体と impl ブロック:メソッドと関連関数

メソッド構文(&self、&mut self)や ServerNode::new() のような関連関数を学びます。

構文

impl StructName { fn new() -> Self {} fn method(&self) {} }

パラメータと値

この構文の主な構成要素と指定可能な値:

パラメータ型説明
&selfReceiver構造体インスタンスを不変で借用します。
&mut selfReceiver構造体インスタンスを可変で借用します。

そのまま実行できるコード例

Compilra で実行可能

Rust をローカルにインストールせずに、この動作する完全なコード例を直接実行できます:

struct ServerNode {
    hostname: String,
    port: u16,
    is_active: bool,
}

impl ServerNode {
    // Associated function (constructor)
    fn new(host: &str, port: u16) -> Self {
        ServerNode {
            hostname: String::from(host),
            port,
            is_active: false,
        }
    }

    // Mutable method
    fn start(&mut self) {
        self.is_active = true;
        println!("[NODE] {}:{} is now active.", self.hostname, self.port);
    }

    // Immutable method
    fn status(&self) -> &str {
        if self.is_active { "ONLINE" } else { "OFFLINE" }
    }
}

fn main() {
    let mut node = ServerNode::new("api-primary", 8080);
    println!("Status before: {}", node.status());
    node.start();
    println!("Status after:  {}", node.status());
}
期待される出力:
Status before: OFFLINE
[NODE] api-primary:8080 is now active.
Status after:  ONLINE

動作のしくみ: ステップ解説

  • 7〜15行目: ServerNode::new コンストラクタが Self を返します。
  • 18〜21行目: fn start(&mut self) が構造体フィールドをその場で変更します。
  • 24〜26行目: fn status(&self) がフィールドを不変借用します。

重要ポイント

  • impl ブロックは型にメソッドを関連付けます。
  • self を取らない関連関数は :: 構文(例:Type::new())で呼び出します。
  • &self を取るメソッドはドット構文(例:instance.status())で呼び出します。

よくある間違い: 不変の構造体変数に対して &mut self メソッドを呼び出すこと

&mut self メソッドを使うには構造体インスタンスを let mut で宣言する必要があります。

❌ 誤り
let node = ServerNode::new(...);
node.start(); // Compile Error: cannot borrow as mutable
✅ 正しい例
let mut node = ServerNode::new(...);
node.start();

関連するRustチュートリアルとコンパイラ

Compilra で Rust を実行・テストする

Compilraのクラウドコンパイラ上で事前設定した標準入力 (stdin) を使ってこのコードを実行できます。