变量
用 let 关键字定义变量,比如:
let num = 5;
上面的变量其实变不了(类似C语言里的const),也不能被再次赋值,如果想变,需要加入关键字 mut,如:
let mut num = 5;
常量
常量运行时不能改(类似C语言里的宏定义),不能用mut关键字修饰,定义时必须指定类型,可以是表达式:
const NUMBER: u32 = 10;
const THREE_HOURS_IN_SECONDS: u32 = 60 * 60 * 3;
赋值时改变类型是不可以的,可以重新使用let关键字:
let mut spaces = " ";
spaces = spaces.len();
这么写OK。
let mut spaces = " ";
let spaces = spaces.len();
类型
因为Rust是静态语言,编译时知道所有变量的类型,类型分scalar和compound两种。
let guess = "42".parse().expect("Not a number!");
上图报错的原因就是没指定类型,应改为:
let guess: u32 = "42".parse().expect("Not a number!");
scalar type:
单类型,有四种,分别是:整型、浮点型、布尔、字符。
整型
长度 | 有符号 | <