1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
//rust 使用所有权机制管理内存,在编译过程中编译器会根据所有权规则对内存使用进行检查
//堆和栈
//编译过程中数据大小固定在栈上分配
//编译过程中数据大小不固定分配在栈上
//作用域
//String内存回收
//移动
//clone
//栈上数据拷贝
//函数和作用域
//指针在栈中,指针指向的值在堆中
fn main()
{
let x :i32 = 1;//栈
{
let y :i32 = 1;
println!("x = {}",x);
println!("y = {}",y);
}
//脱离作用域
//println!("y = {}",y);

//
//这些方法均为堆上数据拷贝
{
let s1 = String::from("Hello");
//字符串在编译过程中大小不固定,可以变换大小,所以在堆上
s1.push_str("world");
println!("s1 = {}",s1);
//drop析构函数
//String类型离开作用域时候调用drop方法
let s2 = s1;
println!("s2 = {} ",s2);
//s2借用了s1
//报错
//因为只是浅拷贝,相当于移动
//println!("s1 = {}",s1);

//深拷贝
let s3 = s2.clone();
println!("s2 = {}",s2);
println!("s3 = {}",s3);

}
//实现copy方法就能实现栈上拷贝
//copy trait
let a = 1;
let b = a;
println!("a = {} ",a);
println!("b = {} ",b);
//常用的具有copy trait特征的有所有的整形、浮点型、布尔值、字符类型、元组



}

  • 函数作用域
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    //如果将string参数返回则可以使用
    fn takes_ownership(som_string: String) {
    //fn takes_ownership(some_string: String) -> String {
    println!("{}",some_string);
    //some_string
    }
    fn makes_copy(i : i32) {
    println!("i = {}",i);
    }
    fn main () {
    let s = String::from("Hello");
    takes_ownership(s);
    //打印不了s
    //因为函数已经退出了它的作用域
    //也就是内存回收了
    //println!("s = {}",s);

    let x = 5;
    makes_copy(x);
    //在栈上的内存
    //具有copy trait的类型,相当于函数调用是拷贝
    println!("x");
    }