《Rust权威指南》学习笔记之第3章 通用编程概念
常量与变量
变量默认不可变。
let x=5;
x=6; //错误
let mut x=5;
x=6; //正确
常量总是不可变。
const MAX_POINTS: u32 = 100_000;
第二个变量隐藏(shadow)第一个变量。
let x=5;
let x = x+1;
let x = x*2;
let spaces = " ";
let spaces = spaces.len();
let mut spaces = " ";
spaces = spaces.len(); //错误
数据类型
标量类型(scalar)
单值类型。整数、浮点数、布尔值和字符。
整数类型
i8, u8
i16, u16
i32(默认), u32
i64, u64
isize, usize(与程序运行的目标平台架构一致,64位,32位)
整形字面量 | 示例 |
---|---|
Decimal | 98_222 |
Hex | 0xff |
Octal | 0o77 |
Binary | 0b1111_0000 |
Byte(u8 only) | b’A’ |
浮点数类型
IEEEE-754标准
f32
f64(默认)
布尔类型
bool(true和false),单字节空间。
字符类型
char,单引号指定,单个字符,4字节,Unicode标量值。字符串,双引号指定。
复合类型(compound)
组合类型。元组(tuple)和数组(array)。
元组类型
不同类型多值组合,固定长度,不可增删。
let tup: (i32, f64, u8) = (500, 6.4, 1);
let (x, y, z) = tup; //解构(destructuring)
let one = x.2; //点号(.)访问元组中的指
数组类型
存储相同类型的多指集合,固定长度,不可增删。
动态数组(vector)类型,允许自由调整大小。
let a = [1, 2, 3, 4, 5]; //栈上分配
let a: [i32; 5] = [1, 2, 3, 4, 5];
let a = [3; 5]; //5个3
let second = a[1];
函数
命名
蛇形命名法(snake case)规范函数和变量名称。只使用小写字母,下划线分隔单词。
fn main() {
println!(“Hello, world!”);
another_function();
}
fn another_function() {
println!(“Another function.”);
}
函数参数
parameter和argument。
fn main() {
another_function(5, 6);
}
fn another_function(x: i32, y: i32) {
println!(“The value of x is: {}”, x);
println!(“The value of y is: {}”, y);
}
语句和表达式
函数体由若干语句(statemen)组成,可以表达式(expression)结尾。
语句指执行操作但不返回值的指令,表达式则指会进行计算并产生指作为结果的指令。
调用函数是表达式,调用宏是表达式,创建新作用域的花括号{}也是表达式。
let y = { //代码块
let x=3; //语句
x+1 //表达式
};
函数返回值
函数返回值可以不用命名,但需->后声明类型。函数返回值等同于函数体最后一个表达式的指。return可以提前返回。
fn plus_one(x: i32) -> i32 {
x+1
//x+1;会报错,默认返回空元组()。
}
注释(comment)
//这是第一种注释方式
/*这是第二种注释方式*/
/*
多行注释
多行注释
多行注释
*/
控制流
if表达式
let number = 6;
if number % 4 == 0 {
println!("number is divisible by 4");
} else if number % 3 == 0 {
println!("number is divisible by 3");
} else if number % 2 == 0 {
println!("number is divisible by 2");
} else {
println!("number is not divisible by 4, 3, 2");
}
let语句中使用if
let continue = true;
let number = if continue {
5
} else {
6
}; //所有if分支可能返回值都必须是同一种类型。
循环重复执行
3种循环:loop、while和for。
loop {
//if...break
}
loop循环返回值
let mut counter = 0;
let result = loop {
counter += 1;
if counter == 10 {
break counter * 2;
}
};
while条件循环
let mut number = 3;
while number != 0 {
number -= 1;
}
for循环遍历集合
let a = [1], 20, 30, 40, 50;
for element in a.iter() {
println!("the value is: {}", element);
}
for number in (1..4).rev() {
println!("{}!", number);
}