---
title: "rust中的ownership, references-and-borrowing,  ifetimes"
author: "simplehappy"
date: "2016-03-17T09:31:48Z"
tags: []
categories: ["编程语言"]
slug: "rust-ownership-references-and-borrowing-ifetimes"
draft: false
lastmod: "2016-03-23T12:36:41Z"
id: 2283714
url: "https://simplehappy.iteye.com/blog/2283714"
---

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`

}
```