Rust编程基础
Rust是一门系统编程语言,专注于安全,尤其是并发安全,支持函数式和命令式以及泛型等编程范式的多范式语言。Rust在语法上和C++类似,但是设计者想要在保证性能的同时提供更好的内存安全。
1.下载安装
Windows版本下载(先安装Visual Studio,社区版免费):
https://static.rust-lang.org/rustup/dist/x86_64-pc-windows-msvc/rustup-init.exe
Linux版本下载(Ubuntu为例):
$ sudo apt update $ sudo apt install build-essential curl vim $ curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
安装Windows、Linux差不多,安装出现过程如下选项:
Current installation options: default host triple: x86_64-unknown-linux-gnu default toolchain: stable (default) profile: default modify PATH variable: yes 1) Proceed with installation (default) 2) Customize installation 3) Cancel installation >1
我们选择1,默认安装,之后会进行在线安装,离线安装等访问参考官网Get-Started。
在Linux版本,安装成功后需要运行一下命令(Windows不需要此步骤):
Rust is installed now. Great! To get started you may need to restart your current shell. This would reload your PATH environment variable to include Cargo's bin directory ($HOME/.cargo/bin). To configure your current shell, run: source "$HOME/.cargo/env"
即,命令行运行:
source "$HOME/.cargo/env"
2.基础示例
方法1:
$ cargo new hello-rust $ cargo run Compiling hello-rust v0.1.0 (/Users/ag_dubs/rust/hello-rust) Finished dev [unoptimized + debuginfo] target(s) in 1.34s Running `target/debug/hello-rust` Hello, world!
Note: 在run之前,也可以使用build, cargo build编译Debug版本, cargo build --release,编译release版本。
方法2(以Linux为例,Windows类似):
$ vim hello.rs
在hello.rs文件中编写并保存如下内容:
1 fn main() 2 { 3 println!("Hello World."); 4 }
编译:
$ rustc hello.rs $ ./hello Hello World.
3. 打印输出
1 fn main() 2 { 3 println!("Bob, 18."); 4 println!("{}, {}.", "Bob", 18); 5 println!("{0}, {1}.", "Bob", 18); 6 println!("{Name}, {Age}.", Name = "Bob", Age = 18); 7 }
4. 数据类型
位长度(bit) | 有符号 | 无符号 |
8 | i8 | u8 |
16 | i16 | u16 |
32 | i32 | u32 |
64 | i64 | u64 |
128 | i128 | u128 |
arch | isize | usize |
其中isize和usize取决于平台架构,32位处理器是32,64位处理器是64.
5. 注释
// 方式1. /// 方式2. /* 方式3. */ /** * 方式4. * 多行注释. */
6. 变量常量
6.1 局部变量
1 // 不可变变量 2 let a; 3 let b = true; 4 let c: bool = true; 5 let (x, y) = (1, 2); 6 a = 1234; 7 8 // 可变变量 9 let mut z = 5; 10 z = 6;
6.2 全局变量
1 // 静态变量(不可变) 2 static Num: i32 = 7; 3 4 // 静态变量(可变) 5 static mut Num: i32 = 8; 6 Num = 9;
6.3 常量
1 // 常量 2 const Num: i32 = 10;
6.4 占位符
1 // 下划线"_",表示占位符 2 let a = [4, 5, 6]; 3 let [b, _, c] = a; // b = 4, c = 6.
7. 其他类型
7.1 数组
1 let a = [1, 2, 3]; // a[0] = 1, a[1] = 2, a[2] = 3 2 let mut b = [1, 2, 3]; 3 4 let c: [int; 3] = [1, 2, 3]; // [类型; 数组长度] 5 6 let d: ["my value"; 3]; // ["my value", "my value", "my value"]; 7 8 let e: [i32; 0] = []; // 空数组 9 10 println!("{:?}", a); // [1, 2, 3]
7.2 元组
1 let a = (1, 1.5, true, 'a', "Hello, world!"); 2 // a.0 = 1, a.1 = 1.5, a.2 = true, a.3 = 'a', a.4 = "Hello, world!" 3 4 let b: (i32, f64) = (1, 1.5); 5 6 let (c, d) = b; // c = 1, d = 1.5 7 let (e, _, _, _, f) = a; // e = 1, f = "Hello, world!", _ 作为占位符使用,表示忽略该位置的变量 8 9 let g = (0,); // 只包含一个元素的元组 10 11 let h = (b, (2, 4), 5); // ((1, 1.5), (2, 4), 5) 12 13 println!("{:?}", a); // (1, 1.5, true, 'a', "Hello, world!")
7.3 切片
1 let a: [i32; 4] = [1, 2, 3, 4]; 2 3 let b: &[i32] = &a; // 全部 4 let c = &a[0..4]; // [0, 4) 5 let d = &a[..]; // 全部 6 7 let e = &a[1..3]; // [2, 3] 8 let e = &a[1..]; // [2, 3, 4] 9 let e = &a[..3]; // [1, 2, 3]
7.4 字符串
1 let a = "Hello, world!"; // a: &'static str 2 let b: &str = "你好, 世界!"; 3 let s1 = "Hello, world!".to_string(); 4 let s2 = String::from("Hello, world!");
8. 函数
// 结构形式 fn <函数名> (<参数>) {<函数体>}
1 fn test(x: i32, y: i32) -> i32 2 { 3 return x + y; 4 } 5 6 fn main() 7 { 8 let val = test(5, 6); 9 10 println!("The value is: {}.", val); 11 }
9. 条件语句
形式1:
if...else if...else
1 let val = 5; 2 3 if val < 4 { 4 val = 4; 5 } 6 else if val < 6 { 7 val += 2; 8 } 9 else { 10 val = 10; 11 }
形式2:
match
1 let tshirt_width = 20; 2 3 let tshirt_size = match tshirt_width { 4 16 => "S", // check 16 5 17 | 18 => "M", // check 17 and 18 6 19 ... 21 => "L", // check from 19 to 21 (19,20,21) 7 22 => "XL", 8 _ => "Not Available", 9 }; 10 11 println!("{}", tshirt_size); // L
10. 循环
10.1 while
1 let mut a = 1; 2 3 while a <= 10 { 4 println!("Current value : {}", a); 5 a += 1; // Rust不支持++/--自增自减语法 6 }
10.2 for
1 for a in 0..10 { // (a = 0; a <10; a++) 2 println!("Current value : {}", a); 3 }
10.3 loop
1 let mut a = 0; 2 3 loop { 4 if a == 0 { 5 println!("Skip Value : {}", a); 6 a += 1; 7 continue; 8 } else if a == 2 { 9 println!("Break At : {}", a); 10 break; 11 } 12 println!("Current Value : {}", a); 13 a += 1; 14 } 15 16 // Skip Value : 0 17 // Current Value : 1 18 // Break At : 2
11. 运算符
11.1 算数运算符
+, -, *, /, %
1 let a = 5; 2 3 let b = a + 1; // 6 4 let c = a - 1; // 4 5 let d = a * 2; // 10 6 let e = a / 2; // 2 not 2.5 7 let f = a % 2; // 1 8 9 let g = 5.0 / 2.0; // 2.5
11.2 比较运算符
==, =, !=, <, >, <=, >=
1 let a = 1; 2 let b = 2; 3 4 let c = a == b; // false 5 let d = a != b; // true 6 let e = a < b; // true 7 let f = a > b; // false 8 let g = a <= a; // true 9 let h = a >= a; // true 10 11 let i = true > false; // true 12 let j = 'a' > 'A'; // true
11.3 逻辑运算符
!, &&, ||
1 let a = true; 2 let b = false; 3 4 let c = !a; // false 5 let d = a && b; // false 6 let e = a || b; // true
11.4 位运算符
&, |, ^, <<, >>
1 let a = 1; 2 let b = 2; 3 4 let c = a & b; // 0 (01 && 10 -> 00) 5 let d = a | b; // 3 (01 || 10 -> 11) 6 let e = a ^ b; // 3 (01 != 10 -> 11) 7 let f = a << b; // 4 (左移 -> '01'+'00' -> 100) 8 let g = a >> a; // 0 (右移 -> 01 -> 0)
11.5 赋值运算符
1 let mut a = 2; 2 3 a += 5; // 2 + 5 = 7 4 a -= 2; // 7 - 2 = 5 5 a *= 5; // 5 * 5 = 25 6 a /= 2; // 25 / 2 = 12 not 12.5 7 a %= 5; // 12 % 5 = 2 8 9 a &= 2; // 10 && 10 -> 10 -> 2 10 a |= 5; // 010 || 101 -> 111 -> 7 11 a ^= 2; // 111 != 010 -> 101 -> 5 12 a <<= 1; // '101'+'0' -> 1010 -> 10 13 a >>= 2; // 101̶0̶ -> 10 -> 2
11.6 类型转换运算符
as
1 let a = 15; 2 let b = (a as f64) / 2.0; // 7.5
12. 集合
12.1 新建
1 let v: Vec<i32> = Vec::new(); // 空集合 2 // let v = vec![1, 2, 3]; // 含初始值的集合,vec!是为方便初始化Vec提供的宏。 3 4 println!("第三个元素 {}", &v[2]); // 3 5 println!("第100个元素 {}", &v[100]); // panic error 6 7 assert_eq!(v.get(2), Some(&3)); 8 assert_eq!(v.get(100), None);
12.2 更新
1 let v: Vec<i32> = Vec::new(); 2 v.push(5); 3 v.push(6); 4 v.push(7); 5 v.push(8); 6 v.pop() // 删除最后一个元素
12.3 遍历
1 let v = vec![100, 32, 57]; 2 for i in &v { 3 println!("{}", i); 4 } 5 6 let mut v2 = vec![100, 32, 57]; 7 for i in &mut v2 { 8 *i += 50; 9 }
13. 结构体
1 struct Site { 2 domain: String, 3 name: String, 4 nation: String, 5 found: u32 6 }
14. 枚举类
1 #[derive(Debug)] 2 3 enum Book { 4 Papery, Electronic 5 } 6 7 fn main() { 8 let book = Book::Papery; 9 println!("{:?}", book); // Papery 10 }
15. 错误处理
1 use std::io; 2 use std::io::Read; 3 use std::fs::File; 4 5 fn read_username_from_file() -> Result<String, io::Error> { 6 let mut f = File::open("hello.txt")?; 7 let mut s = String::new(); 8 f.read_to_string(&mut s)?; 9 Ok(s) 10 }
16. 泛型
1 fn largest<T>(list: &[T]) -> T { 2 let mut largest = list[0]; 3 4 for &item in list.iter() { 5 if item > largest { 6 largest = item; 7 } 8 } 9 10 largest 11 } 12 13 fn main() { 14 let number_list = vec![34, 50, 25, 100, 65]; 15 16 let result = largest(&number_list); 17 println!("The largest number is {}", result); 18 19 let char_list = vec!['y', 'm', 'a', 'q']; 20 21 let result = largest(&char_list); 22 println!("The largest char is {}", result); 23 }
17. 文件IO
17.1 文件读
1 use std::fs; 2 3 fn main() { 4 let text = fs::read_to_string("D:\\text.txt").unwrap(); 5 println!("{}", text); 6 }
17.2 文件写
1 use std::fs; 2 3 fn main() { 4 fs::write("D:\\text.txt", "FROM RUST PROGRAM") 5 .unwrap(); 6 }
18. 面向对象
1 second.rs 2 pub struct ClassName { 3 field: i32, 4 } 5 6 impl ClassName { 7 pub fn new(value: i32) -> ClassName { 8 ClassName { 9 field: value 10 } 11 } 12 13 pub fn public_method(&self) { 14 println!("from public method"); 15 self.private_method(); 16 } 17 18 fn private_method(&self) { 19 println!("from private method"); 20 } 21 } 22 main.rs 23 mod second; 24 use second::ClassName; 25 26 fn main() { 27 let object = ClassName::new(1024); 28 object.public_method(); 29 } 30 31 // from public method 32 // from private method
19. 并发编程
1 use std::thread; 2 use std::time::Duration; 3 4 fn spawn_function() { 5 for i in 0..5 { 6 println!("spawned thread print {}", i); 7 thread::sleep(Duration::from_millis(1)); 8 } 9 } 10 11 fn main() { 12 thread::spawn(spawn_function); 13 14 for i in 0..3 { 15 println!("main thread print {}", i); 16 thread::sleep(Duration::from_millis(1)); 17 } 18 } 19 20 // main thread print 0 21 // spawned thread print 0 22 // main thread print 1 23 // spawned thread print 1 24 // main thread print 2 25 // spawned thread print 2