We call the &T type a ‘reference’, and rather than owning the resource, it borrows ownership
error: cannot borrow `v` as mutable more than once at a time [E0499]
fn main() {
let mut v = vec![1, 2, 3];
let v1 = &mut v;
for i in &mut v {
*i += 1;
}
}
fn main() {
let mut v = vec![1, 2, 3];
for i in &mut v { 借用生命周期只在循环内
*i += 1;
}
let v1 = &mut v;
}
fn main() {
struct Point {
x: i32,
}
let mut p = Point{x: 1};
{
let plus = |x: i32| x + p.x; //borrow
println!("{}", plus(1));
}
{
let mut plus = |x: i32| {p.x += x; p.x}; //mut borrow
println!("{}", plus(1));
}
{
let plus = move|x: i32| x + p.x; //ownship move
println!("{}", plus(1));
}
let y = &p; //error: use of moved value: `p`
}
本文探讨了Rust语言中的生命周期概念及其借用规则,并通过具体的代码示例解释了如何正确处理变量的借用与所有权转移,避免编译时错误。
588

被折叠的 条评论
为什么被折叠?



