PDF版 ePub版

# 可变性

let x = 5;
x = 6; // error!

let mut x = 5;

x = 6; // no problem!

let mut x = 5;
let y = &mut x;

y 是一个绑定到一个可变引用的不可变值，这意味着你不可以将 y 绑定到其他 ( y = &mut z )，但是你可以改变绑定到 y上的东西 ( *y=5 ).细微的差别。

let mut x = 5;
let mut y = &mut x;

let (mut x, y) = (5, 6);

fn foo(mut x: i32) {

## 内部和外部可变性

use std::sync::Arc;

let x = Arc::new(5);
let y = x.clone();

You may have one or the other of these two kinds of borrows, but not both at the same time:

one or more references (&T) to a resource.
exactly one mutable reference (&mut T)

use std::cell::RefCell;

let x = RefCell::new(42);

let y = x.borrow_mut();

RefCell 用 borrow_mut() 函数来将 &mut 引用传递到它包含的东西中。那样不危险吗？如果那样做会怎样：

use std::cell::RefCell;

let x = RefCell::new(42);

let y = x.borrow_mut();
let z = x.borrow_mut();

## 字段级可变性

struct Point {
x: i32,
mut y: i32, // nope
}

struct Point {
x: i32,
y: i32,
}

let mut a = Point { x: 5, y: 6 };

a.x = 10;

let b = Point { x: 5, y: 6};

b.x = 10; // error: cannot assign to immutable field b.x

use std::cell::Cell;

struct Point {
x: i32,
y: Cell<i32>,
}

let point = Point { x: 5, y: Cell::new(6) };

point.y.set(7);

println!("y: {:?}", point.y);