`

rust中的ownership, references-and-borrowing, ifetimes

    博客分类:
  • rust
 
阅读更多

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`

}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics