Rust官方教程 https://kaisery.github.io/trpl-zh-cn/ch03-05-control-flow.html 官方练习 https://github.com/rust-lang/rustlings
Rustup
安装镜像 powershell
$Env:RUSTUP_DIST_SERVER = "https://mirrors.tuna.tsinghua.edu.cn/rustup"
.\rustup-init.exebash
RUSTUP_DIST_SERVER=https://mirrors.tuna.tsinghua.edu.cn/rustup rustup install stable创建项目
cargo new world_hello
cd world_hello
cargo runcargo依赖代理
export https_proxy=http://127.0.0.1:7890 http_proxy=http://127.0.0.1:7890 all_proxy=socks5://127.0.0.1:7891配置国内镜像 $HOME/.cargo/config.toml
[source.crates-io]
replace-with = 'mirror'
[source.mirror]
registry = "sparse+https://mirrors.tuna.tsinghua.edu.cn/crates.io-index/"
[registries.mirror]
index = "sparse+https://mirrors.tuna.tsinghua.edu.cn/crates.io-index/"语法
HelloWorld
fn greet_world() {
let southern_germany = "Grüß Gott!";
let chinese = "世界,你好";
let english = "World, hello";
let regions = [southern_germany, chinese, english];
for region in regions.iter() {
println!("{}", ®ion);
}
}
fn main() {
greet_world();
}Rust中默认变量不可变,若要让变量可变,需要添加mut关键字;若有变量定义却未使用,需要在变量名前加_来忽略警告。
fn main() {
let _y = 1;
let mut x = 5;
println!("The value of x is: {}", x);
x = 6;
println!("The value of x is: {}", x);
}变量基本类型
数值类型
整型 i<bit>如i8到i128;无符号整型u8到u128;isize和usize表示基于机器架构来决定变量大小。
数值类型综合案例
fn main() {
// 编译器会进行自动推导,给予twenty i32的类型
let twenty = 20;
// 类型标注
let twenty_one: i32 = 21;
// 通过类型后缀的方式进行类型标注:22是i32类型
let twenty_two = 22i32;
// 只有同样类型,才能运算
let addition = twenty + twenty_one + twenty_two;
println!("{} + {} + {} = {}", twenty, twenty_one, twenty_two, addition);
// 对于较长的数字,可以用_进行分割,提升可读性
let one_million: i64 = 1_000_000;
println!("{}", one_million.pow(2));
// 定义一个f32数组,其中42.0会自动被推导为f32类型
let forty_twos = [
42.0,
42f32,
42.0_f32,
];
// 打印数组中第一个值,并控制小数位为2位
println!("{:.2}", forty_twos[0]);
}rust不会隐式转换数据类型,所有数据类型的转换必须是显式指定的。
序列
// 包含5
for i in 1..=5 {
println!("{}",i);
}
// 不包含5
for i in 1..5 {
println!("{}",i);
}字符类型
在rust中,字符默认使用Unicode编码,使用单引号''包裹,占用4字节。
fn main() {
let c = 'z';
let z = 'ℤ';
let g = '国';
let heart_eyed_cat = '😻';
}单元类型
单元类型的表示方式是(),表示空,没有;一个函数若是没有返回类型,则默认会返回一个单元类型()
语句和表达式
在Rust中,语句表示通常变量声明,而表达式表示一种计算;他们之间最大的差异是:表达式总要返回值。还有一个语法上的差异是:语句后带分号,而表达式后不带分号。
fn main() {
assert_eq!(ret_unit_type(), ())
}
fn ret_unit_type() {
let x = 1;
// if 语句块也是一个表达式,因此可以用于赋值,也可以直接返回
// 类似三元运算符,在Rust里我们可以这样写
let y = if x % 2 == 1 {
"odd"
} else {
"even"
};
// 或者写成一行
let z = if x % 2 == 1 { "odd" } else { "even" };
let y = {
let x = 3;
x + 1 // 若这行最后带了分号,则会成为语句而不会返回值了
};
println!("The value of y is: {}", y);
}函数
一图胜千言
rust是静态类型语言,函数的参数类型必须显式指定。
fn add(i: i32, j: i32) -> i32 {
i + j
}