0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

(DAY24) 俺と学ぶRust言語~借用と参照~

Posted at

今日の内容

  • 借用と参照

はじめに

前回はファイルI/Oについて学びました。
今回は借用と参照について学びます。
Rustを学んでいると「借用」と「参照」という概念に出会います。初めて聞くと難しそうですが、これらはRustが安全で効率的なプログラムを作るための重要な仕組みです。

借用と参照とは?

まずは、それぞれの概念を簡単に説明します。

  • 参照(reference): ある値を「所有権を持たずに利用する」仕組み
  • 借用(borrowing): 他の部分が所有する値を一時的に借りて利用すること

Rustでは、値を複数の場所で安全に利用するために、参照と借用が欠かせません。

参照の基本構文

Rustで参照を使う際は、&を使います。

fn main() {
    let x = 42;          // xを定義
    let x_ref = &x;      // xの参照を作る
    println!("{}", x_ref); // 参照を使って値を表示
}

ここでのポイント:

  • &xは「xを借用して参照を作る」という意味
  • xの所有権はそのまま、x_refは値へのポインタのような役割を果たす

可変参照

参照には 不変参照可変参照 の2種類があります。

  • 不変参照: 参照先の値を変更できない
  • 可変参照: 参照先の値を変更できる

以下の例で確認しましょう:

fn main() {
    let mut x = 42;        // xを可変にする
    let x_ref = &mut x;    // xの可変参照を作る
    *x_ref += 1;           // 参照を使って値を変更
    println!("{}", x_ref); // 43
}
  • &mutは「可変参照」を作る
  • *で参照先の値を操作できる

借用ルール

Rustには「借用ルール」があります。このルールを守ることで、コンパイル時にメモリの問題を防げます。

同時に複数の可変参照は作れない

fn main() {
    let mut x = 42;  // xを可変にする
    let x1 = &mut x; // xの可変参照を作る
    let x2 = &mut x; // エラー
    println!("{} {}", x1, x2)
}

不変参照と可変参照を同時に作れない

fn main() {
    let mut x = 42;  // xを可変にする
    let x1 = &x;     // 不変参照
    let x2 = &mut x; // エラー
    println!("{} {}", x1, x2);
}

おわりに

今回はRustでの借用と参照について学びました。
次回は「write vs write_all」について学びましょう。
ご精読ありがとうございました。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?