From 39fef5e8565d844cc38471a2d846d27c864e81a2 Mon Sep 17 00:00:00 2001 From: fw_qaq <82551626+Jack-Zhang-1314@users.noreply.github.com> Date: Mon, 28 Nov 2022 03:20:56 -0500 Subject: [PATCH] doc: update rust.md (#181) (#20) --- docs/rust.md | 149 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 149 insertions(+) diff --git a/docs/rust.md b/docs/rust.md index 4cd1d2a..94e8c86 100644 --- a/docs/rust.md +++ b/docs/rust.md @@ -354,6 +354,14 @@ rand.capacity() // => 13 以字节为单位计算字符串的容量 +### with_capacity() + +```rust +let s = String::with_capacity(10); +``` + +指定一个足够大的容量值,来减少内存拷贝 + ### .contains() ```rust @@ -484,6 +492,147 @@ let arr = vec![ `drain(range)` | 删除 `vec` 中指定范围的元素,同时返回一个迭代该范围所有元素的迭代器 `split_off(index)` | 切分 `vec`,索引左边的元素保留在原 `vec` 中(含索引),索引右边的元素(不含索引)在返回的 `vec` 中 +Rust HashMap\ +-------- + +### 使用 + +```rust +use std::collections::HashMap; + +fn main() { + let mut map: HashMap = HashMap::new(); + map.insert(String::from("blue"), 100); + // 查询Yellow对应的值,若不存在则插入默认值 + let v: &mut i32 = + map.entry("Yellow".to_string()).or_insert(5); + let v: &mut i32 = + map.entry("Yellow".to_string()).or_insert(50); // 不会修改值 +} +``` + +### 获取元素 + +```rust +let mut scores = HashMap::new(); + +scores.insert(String::from("Blue"), 10); +scores.insert(String::from("Yellow"), 50); + +let team_name = String::from("Blue"); +let score: Option<&i32> = scores.get(&team_name); +``` + +### 遍历 + +```rust +let mut scores = HashMap::new(); + +scores.insert(String::from("Blue"), 10); +scores.insert(String::from("Yellow"), 50); + +for (key, value) in &scores { + println!("{}: {}", key, value); +} +``` + +### vec -> HashMap + +```rust +let teams_list = vec![ + ("中国队".to_string(), 100), + ("美国队".to_string(), 10), + ("日本队".to_string(), 50), +]; +let teams_map: HashMap<_,_> = + teams_list.into_iter().collect(); +``` + +---- + +```rust +let teams = vec![String::from("blue"),String::from("red")]; +let intial_scores = vec![10,50]; +let scores:HashMap<_,_> = + teams.iter().zip(intial_scores.iter()).collect(); +``` + +Option & Result +-------- + +### Option + +```rust +enum Option { + Some(T), + None, +} +``` + +#### 使用 + +```rust +fn main(){ + let a = Some(5); + // 直接获取原始值 + println!("{}", a.unwrap()); + // 给出错误信息 + let x: Option<&str> = None; + x.expect("fruits are healthy"); // panics 带有 `fruits are healthy` +} +``` + +### Result + +```rust +enum Result { + Ok(T), + Err(E), +} +``` + +#### 使用 + +```rust +use std::fs::File; + +fn main() { + let f: Result = File::open("hello.txt"); + let f = match f { + Ok(file) => file, + Err(error) => { + panic!("Problem opening the file: {:?}", error) + }, + }; +} +``` + +### 宏 `?` + +`?` 只能用于返回结果是 Result 或者 Option 的函数,或者实现了 Try 类型 + +```rust +use std::fs::File; +use std::io::{self, Read}; + +fn read_username_from_file() -> Result { + let mut s = String::new(); + File::open("hello.txt")?.read_to_string(&mut s)?; + Ok(s) +} +``` + +---- + +```rust +fn first(arr: &[i32]) -> Option<&i32> { + let v = arr.get(0)?; + Some(v) +} +``` + + + 枚举 --------