【Rust】学习笔记二:变量绑定与解构

12/31/2021 Rust

# 变量绑定

JavaScript 中使用 var a = "hello world"的形式给变量a赋值,在 Rust 中使用let a = "hello world",给变量a进行变量绑定:绑定当前的内存空间地址到变量 aa具有所有权

# 变量可变性

a 是不可变的

let a = "hello world";
1

使用 mut声明变量可变

let mut a = "hello world";
a = "hello world";
1
2

# 变量解构

fn main() {
    let (a, mut b): (bool,bool) = (true, false);
    // a = true,不可变; b = false,可变
    println!("a = {:?}, b = {:?}", a, b);

    b = true;
    assert_eq!(a, b);
}
1
2
3
4
5
6
7
8

# 变量和常量

  1. 常量使用const关键字
  2. 常量需要声明类型。
  3. 常量不仅仅默认不可变,而且自始至终不可变

例如:

const MAX_POINTS: u32 = 100_000;
1

# 变量遮蔽(shadowing)

Rust 允许声明相同的变量名,在后面声明的变量会遮蔽掉前面声明的。

fn main() {
    let x = 5;
    // 在main函数的作用域内对之前的x进行遮蔽
    let x = x + 1; // x -> 6

    {
        // 在当前的花括号作用域内,对之前的x进行遮蔽
        let x = x * 2; // x -> 12
        println!("The value of x in the inner scope is: {}", x);
    }

    println!("The value of x is: {}", x);
}
1
2
3
4
5
6
7
8
9
10
11
12
13

mut的区别:

  1. let 每次都会进行内存分配,只是变量名称恰好相同
  2. mut 修改同一个内存地址上的值,并不会发生内存对象的再分配,性能要更好。

示例:假设有一个程序要统计一个空格字符串的空格数量:

// 字符串类型
let spaces = "   ";
// usize数值类型
let spaces = spaces.len();
1
2
3
4

这是允许的,因为开辟了两个内存空间,前者存储字符串类型,后者存储数值类型。如果换成 mut

let mut spaces = "   ";
spaces = spaces.len();
1
2

会报错:

➜  world_hello git:(master) ✗ cargo run
   Compiling world_hello v0.1.0 (/Users/user/my-rust/world_hello)
error[E0308]: mismatched types
 --> src/main.rs:3:14
  |
3 |     spaces = spaces.len();
  |              ^^^^^^^^^^^^ expected `&str`, found `usize`

For more information about this error, try `rustc --explain E0308`.
error: could not compile `world_hello` due to previous error
1
2
3
4
5
6
7
8
9
10

因为 Rust 对类型的要求很严格,不允许将字符串类型赋值给整数类型 usize

Last Updated: 2/21/2022, 11:35:56 AM