t_wの輪郭

Feedlyでフォローするボタン
fn main() {
    let s = String::from("hello");
    change(&s);
}

fn change(some_string: &String) {
    some_string.push_str(", world");
    /*
    error[E0596]: cannot borrow `*some_string` as mutable, as it is behind a `&` reference
    --> src\main.rs:7:5
    |
    6 | fn change(some_string: &String) {
    |                        ------- help: consider changing this to be a mutable reference: `&mut String`
    7 |     some_string.push_str(", world");
    |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `some_string` is a `&` reference, so the data it refers to cannot be borrowed as mutable
    */
}

ベクタの要素を不変変数借用した場合は、そのベクタの要素を変更・追加できなくなる

let mut v = vec![1, 2, 3, 4, 5];
let first = &v[0];
v.push(6);
println!("The first element is: {}", first);
/*
error[E0502]: cannot borrow `v` as mutable because it is also borrowed as immutable
  --> src\main.rs:23:5
   |
21 |     let first = &v[0];
   |                  - immutable borrow occurs here
22 | 
23 |     v.push(6);
   |     ^^^^^^^^^ mutable borrow occurs here
24 | 
25 |     println!("The first element is: {}", first);
   |                                          ----- immutable borrow later used here
*/