47. 語法 程式碼 輸出
immutable borrowing
fn main() {
let x = 10;
let y = &x;
println!("{}", y);
}
10
mutable borrowing
fn main() {
let mut x = 10;
{
let y = &mut x;
*y += 1;
}
println!("{}", x);
}
11
immutable borrowing
on function
fn print_first_elem(v: &Vec<i32>) {
println!("{}", v[0]);
}
fn main() {
let x = vec![1, 2, 3];
print_first_elem(&x);
println!("{}", x[0]);
}
1
mutable borrowing on
function
fn inc_first_elem(v: &mut Vec<i32>) {
(*v)[0] += 1;
}
fn main() {
let mut x = vec![1, 2, 3];
inc_first_elem(&mut x);
println!("{}", x[0]);
}
2
48. 錯誤範例 程式碼 錯誤訊息
不得修改被借⽤用中的
變數
fn main() {
let mut x = 10;
let y = &x;
x += 1;
println!("{}", x);
}
<anon>:4:5: 4:11 error: cannot
assign to `x` because it is
borrowed [E0506]
<anon>:4 x += 1;
^~~~~~
被借⽤用為可修改的變
數時不得再被借⽤用
fn main() {
let mut x = 10;
{
let y = &mut x;
let z = &x;
}
println!("{}", x);
}
<anon>:5:18: 5:19 error:
cannot borrow `x` as immutable
because it is also borrowed as
mutable [E0502]
<anon>:5 let z = &x;
^