Rust篇章三:变量/常量简单介绍

51 阅读2分钟

一、变量和可变性

默认情况下变量是不可变的

Rust中的变量默认是不可变的。 目的是为了能够让你安全且方便地写出复杂、甚至是并行的代码。 当一个变量是不可变的时,一旦它被绑定到某个值上面,这个值就再也无法被改变。

1、熟悉下变量变动后的报错

powershell切换到项目空间,运行: cargo new variables

image.png

切换到variables下,使用代码编辑工具修改src/main.rs:

fn main() {
	let x = 5;
    println!("The value of x is: {}", x);
	x = 6;
	println!("The value of x is:{}", x);
}

编译运行:cargo run

image.png

2、使用mut使变量可变

2.1 使用mut变量,为变量赋值

修改src/main.rs如下:

fn main() {
	let mut x = 5;
    println!("The value of x is: {}", x);
	x = 6;
	println!("The value of x is:{}", x);
}

编译运行:cargo run

image.png

2.2 使用mut变量,不可以改变变量的类型赋值

当然,mut申明后,不可以改变变量的类型: 修改src/main.rs如下:

fn main() {
	let mut spaces = "   ";

        spaces = spaces.len();
	
	println!("The value of x is:{}", spaces);
}

编译运行:cargo run

image.png

3、通过重定义,遮蔽原有变量

相当于重新建立一个变量,可以改变类型。

修改src/main.rs如下:

fn main() {
	let x = 5;
	
	let x = x + 1;
	
	let x = x * 2;
	
	println!("The value of x is:{}", x);
}

编译运行:cargo run

image.png

也可以改变变量类型:

let spaces = " "; 
let spaces = spaces.len();

常量和变量的区别

  • 必须显示指定数据类型
  • 常量名一般使用大写字母,否则编译器会报 Warning
  • 常量不支持重定义(遮蔽),这和变量是不同的。
  • 常量只能设置为常量表达式。 常量表达式如下:
const NUM: i32 = 5;		// const NUM = 5i8	编译不通过
const PI: f64 = 3.14;
const LOVE: &str = "I love Rust!";

Rust 对常量的命名约定是全部大写,单词之间使用下划线,并且可以在数字文字中插入下划线以提高可读性

const MAX_POINTS: u32 = 100_000;

参考文献: [Rust官网-变量和可变性]