本人于2024年9月29日参加清华大学主办的操作系统训练营,由此博客来记录我的学习历程
day0
我参考的rust学习教程:【Rust编程语言入门教程(Rust语言/Rust权威指南配套)【已完结】】 https://www.bilibili.com/video/BV1hp4y1k7SV/?p=37&share_source=copy_web&vd_source=f3e0def7125bc57c729dfe457f662af8
HashMap
HashMap<K,v>
一个键(key)对应一个值(value)
use std::collections::HashMap;
//使用use导入HashMap
fn main() {
let mut scores: HashMap<String,i32> = HashMap::new();
scores.insert(String::from("Blue"),10)
scores.insert(String::from("Yellow"),50)
//数据存储在heap上
}
collect()方法
let scores =
HashMap和所有权
let field_name = String::from("Favorite Color");
let field_value = String::from("Blue");
let mut map = HashMap::new();
//定义了一个可变的HashMap
已经Cop trait的类型(例如i32),值会被复制到HashMap中
对于拥有所有权的值(例如String),值会被移动,所有权会转移给HashMap
map.insert(field_name,field_value);
如果将值的引用插入Hashmap,就不会被移动
map.insert(&field_name,&field_value);
//传入引用
访问HashMap中的值
get()方法
let score = scores.get(&team)
使用for()循环遍历
for(k,v) in &scores{
}
更新HashMap<K,V>
//entry()方法
//scores.entry(String::from("Yellow")),or_insert(50);
let e = scores.entry(String::from("Yellow"));
e.or_insert(50);
scores.entry(String::from("Blue")).or_insert(50);
println!("{:?}",scores);
Error
panic!宏
panic!("crash and burn");
//为了获取带有调试信息的回溯,必须启用调试符号(不带 --release)
### Result枚举
```rust
enum Result<T,E>{
Ok(T),
Err(E),
}
使用match表达式,来处理Result的一种方式:match表达式
use std::fs::File;
fn main(){
let f = File::open("hello.txt");
match f {
OK(file) => file,
Err(error) => {
panic!("Error opening file {:?}",error)
}
};
}
```rust
use std::fs::File;
use std::io::ErrorKind;
fn main
//unwrap()方法
let f = File::open("hello.txt").unwrap();
//expect()方法
let f = File::open("hello.txt").expect('无法打开文件');