ITeye博客

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

simplehappy · 2016-03-17 09:31 · rust · 编程语言 · Markdown

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`

}

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。