所有権と借用
Rust References and Borrowing
Let a function use a value without taking it: & to read, &mut to change.
学べること
- & and &mut
- Borrowing in function calls
- Many readers or one writer
Borrow → what it allows
length(&message)read onlyadd_exclamation(&mut message)can change itlet first = &messagemany readers are fineUse a value without owning it
A reference lets code use a value without owning it. This is called borrowing. &value borrows for reading and &mut value borrows for changing.
length only reads the text, so it takes &str and message can still be used afterwards. add_exclamation needs &mut String to change it. Rust allows many readers at once or one writer, but never both, which rules out data races at compile time.
重要なポイント
- &value borrows for reading.
- &mut value borrows for changing.
- Many readers or one writer, never both.
実行できる Rust のサンプル
Rust
main.rs
fn length(text: &str) -> usize {
text.len()
}
fn add_exclamation(text: &mut String) {
text.push('!');
}
fn main() {
let mut message = String::from("Borrow me");
let size = length(&message); // immutable borrow
println!("{message} has {size} bytes");
add_exclamation(&mut message); // mutable borrow
println!("{message}");
let first = &message;
let second = &message; // many readers are fine
println!("{first} {second}");
}
Borrow me has 9 bytes
Borrow me!
Borrow me! Borrow me!練習
サンプルをオンラインコンパイラーで開き、値を変えたり行を追加したりして、実行する前に出力を予想してみましょう。次に、わざとコードを壊してコンパイラーのメッセージを読んでみてください。
このレッスンを終えましたか?
学習済みにすると進み具合を記録できます。
進み具合はこのブラウザーに保存されています ログインすると、どのデバイスでも引き継げます。
チャレンジで練習する
このレッスンの内容を使って実際の問題を解きましょう。各チャレンジはブラウザで動き、すぐにテストされ、AI のレビューも受けられます。
すべてのチャレンジ