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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93

/// # 临时值
///
/// Basic usage:
///
/// ```
/// pub fn temp() -> i32 {
///     return 1;
/// }
/// let x = &temp();
/// temp() = *x;   // error[E0070]: invalid left-hand side expression
/// ```
pub fn temp() -> i32 {
    return 1;
}

/// # 不变与可变
///
/// Basic usage:
///
/// ```
/// pub fn immutable_and_mutable() {
///     let a = 1;  // 默认不可变
///     // a = 2; // immutable and error: cannot assign twice to immutable variable
///     let mut b = 2;  // 使用mut关键字声明可变绑定
///     b = 3; // mutable
/// }
/// immutable_and_mutable();
/// ```
pub fn immutable_and_mutable() {
    let a = 1;
    // a = 2; // immutable and error
    let mut b = 2;
    b = 3; // mutable
}

/// # 所有权
///
/// Basic usage:
///
/// ```
/// pub fn ownership(){
///     let place1 = "hello";
///     //  ^^ 位置表达式 ^^  值表达式
///     //   ^ 位置上下文  ^  值上下文
///     let place2 = "hello".to_string();
///     let other = place1;    // Copy
///                  // ^^ 位置表达式出现在了值上下文中
///     println!("{:?}", place1);  // place1还可以继续使用
///     let other = place2;    // Move
///                  // ^^ 位置表达式出现在了值上下文中
///     println!("{:?}", place2); // place2不能再被使用,编译出错
/// }
/// ownership();
/// ```
pub fn ownership() {
    let place1 = "hello";
    let place2 = "hello".to_string();
    let other = place1;
    println!("{:?}", other);
    let other = place2;
    println!("{:?}", other); // other value used here after move
}

/// # 引用
///
/// Basic usage:
///
/// ```
/// pub fn reference() {
///     let a = [1,2,3];
///     let b = &a;
///     println!("{:p}", b);  // 0x7ffcbc067704
///     let mut c = vec![1,2,3];
///     let d = &mut c;
///     d.push(4);
///     println!("{:?}", d);
///     let e = &42;
///     assert_eq!(42, *e);
/// }
/// reference();
/// ```
pub fn reference() {
    let a = [1,2,3];
    let b = &a;
    println!("{:p}", b); // 0x7ffcbc067704
    let mut c = vec![1,2,3];
    let d = &mut c;
    d.push(4);
    println!("{:?}", d); // [1, 2, 3, 4]
    let e = &42;
    assert_eq!(42, *e);
}