rust笔记六(rust文档这部分还没写完,,待修改)

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
http://stackoverflow.com/questions/79923/what-and-where-are-the-stack-and-heap

为什么要用pointer
..看原文
接下来解释了什么是 'pass-reference-by-value.'
func foo(&int x) {
    *x = 5
}

func main() {
    i = 1
    foo(&i)
    // what is the value of i here?
}

其它语言中指针的问题 看原文..

Rust中最简单的指针叫reference
let x = 5i;
let y = &x;

println!("{}", *y);
println!("{:p}", y);
println!("{}", y);

打印出5, 5的地址,5(rust会在打印的时候会自动*)

不可变的x可以有多个别名
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的值,故出错.

2.1最佳实践

舸test

end!

你可能感兴趣的:(rust笔记六(rust文档这部分还没写完,,待修改))