Rust常见编程概念-变量与可变性

412 阅读1分钟

今天又继续学习rust了。今天主要是看的常见编程概念中的章节。

总结一下:

1. rust中的变量默认是不可变的(immutable)。

fn main() {
     //声明变量用let 
    let x = 5; 
    println!("The value of x is: {}", x);
    x = 6;
    println!("The value of x is: {}", x);
}

//运行错误
// 不能对不可变变量 x 二次赋值error[E0384]: cannot assign twice to immutable variable `x`
 --> src/main.rs:4:5
  |
2 |     let x = 5;
  |         - first assignment to `x`
3 |     println!("The value of x is: {}", x);
4 |     x = 6;
  |     ^^^^^ cannot assign twice to immutable variable


2. rust中 可变变量 怎么声明呢?在在let 后面加上 mut。

fn main() {
     //添加mut 变成 可变变量 
    let mut x = 5; 
    println!("The value of x is: {}", x);
    x = 6;
    println!("The value of x is: {}", x);
}

//运行结果
$ cargo run
   Compiling variables v0.1.0 (file:///projects/variables)
    Finished dev [unoptimized + debuginfo] target(s) in 0.30 secs
     Running `target/debug/variables`
The value of x is: 5
The value of x is: 6

3.变量隐藏(shadowing),就是再次使用let 创建一个新的变量,可以改变值的类型,复用这个变量名

fn main() {
     //不添加mut 不可变变量
    let x = 5; 
    println!("The value of x is: {}", x);
    //改变x的值
    let x = 12;
    println!("The value of x is: {}", x);    //改变x类型
    let x = "6";
    println!("The value of x is: {}", x);
}

//运行结果
$ cargo run
   Compiling variables v0.1.0 (file:///projects/variables)
    Finished dev [unoptimized + debuginfo] target(s) in 0.30 secs
     Running `target/debug/variables`
The value of x is: 5
The value of x is: 12
The value of x is: 6

注:这里是跟其他编程语言有很大的不同的,像java 这样生命变量会被鄙视的很惨。

4. 常量(constants)常量不能改变,所以不能使用mut,声明的时候使用const关键字而不是使用let关键字。常量可以在任何作用域中声明,包括全局作用域。

Rust 常量的命名规范:使用下划线分隔的大写字母单词,并且可以在数字字面值中插入下划线来提升可读性

fn main() {
const MAX_POINTS: u32 = 100_000;
}