http://doc.rust-lang.org/guide-pointers.html
打印出指针的值(一个地址, referent的地址, 被指者叫做referent)
let x = 5i;
let y = 8i;
let z = &y;
println!("{:p}", z);
location | value |
---|---|
0xd3e030 | 5 |
0xd3e028 | 8 |
0xd3e020 | 0xd3e028 |
println!("{}", x + *z);什么是stack和heap
func foo(&int x) { *x = 5 } func main() { i = 1 foo(&i) // what is the value of i here? }
let x = 5i;
let y = &x;
println!("{}", *y);
println!("{:p}", y);
println!("{}", y);
let x = 5i;
let y = &x;
let z = &x;
可变的x只能有一个别名
let mut x = 5i;
let y = &mut x;
let z = &mut x; // error: cannot borrow `x` as mutable more than once at a time
可变的x只能同时借给一个人, 并且可变的x借出去后(并且在归还之前) 不能做修改.
fn main() {
let x = &mut 5i;
if *x < 10 {
let y = &x;
*x -= 1;
println!("Oh no: {}", y);
return;
}
*x -= 1;
println!("Oh no: {}", x);
}
It gives this error:
test.rs:5:8: 5:10 error: cannot assign to `*x` because it is borrowed test.rs:5 *x -= 1; ^~ test.rs:4:16: 4:18 note: borrow of `*x` occurs here test.rs:4 let y = &x;在y的作用范围结束时,x被归还.以上代码在归还之前尝试修改x的值,故出错.