{"title": "Rust \u5b66\u4e60\u968f\u7b14", "update_time": "2021-09-22 20:21:01", "tags": "rust", "pid": "354", "icon": "linux.png"}
# Rust 学习随笔 ## Struct ``` // Struct Define struct Article { title: String, auther: String, content: String, clicks : i32, } // Struct Method define impl Article { pub fn get_content(&self) -> &str{ &self.content } } fn main(){ // Struct init let mut article = Article{ title: String::from("hello rust"), auther : String::from("hello rust"), content: String::from("Hello world"), clicks : 0, }; article.clicks += 1; println!("article content is {}", article.get_content()); } ``` ## Tuple 相当于匿名的struct,功能比struct弱,使用起来简单 ``` fn cal_area(dim:(u32, u32)) -> u32 { dim.0 * dim.1 } fn main(){ println!("area is {}", cal_area((1,2))); } ``` ## Enum ``` enum Ipaddr { V4(String), V6(String), } impl Ipaddr { fn ping(&self) { println!("ping .."); } } fn main(){ // Enum test let ip = Ipaddr::V4("129.168.1.1".to_string()); match &ip { Ipaddr::V4(v) => println!("the ip is ipv4"), _ => println!("the ip is ipv6") } ip.ping(); // Option Enum let x = Option::Some("hello"); // same as let x = Some("hello"); let y = x.unwrap_or("haha"); println!("y is {}", y); if let Some("hello") = x { println!("x is hello"); } if let Some("haha") = x{ println!("x is haha"); } } ``` ## Array ``` fn main(){ // array init let a1 = [1,2,3,4]; let mut a2 = [1; 10]; // init array with same value 1 for i in a2 { println!("{}", i); } for i in &mut a2 { *i += 2; } for i in a2 { println!("{}", i); } } ``` ## 容器 * Vector ``` fn main(){ // 初始化 let mut v1 = vec![1, 2, 3, 4]; let mut v2:Vec
= Vec::new(); v2.push(1); v2.push(2); // index println!("first: {}", &v1[1]); match v1.get(2){ //安全索引 Some(e) => println!("element 2 is {}", e), None => println!("element 2 not exists") } // 遍历 println!("print vec"); for i in &v1 { println!("value is {}", i) } println!("mut vec"); for i in &mut v1 { *i += 2; println!("value is {}", i) } } ``` * Map ``` use std::collections::HashMap; fn main(){ // 初始化 let mut score = HashMap::new(); score.insert("Math", 98); score.insert("English", 95); // print map println!("{:?}", &score); // get map value let math_score = score.get("Math"); match math_score { Some(i) => println!("Math score is {}", i), None => println!("Math score is not exists") } // insert when not exists, or_insert return a mutable refrence to the value let num = score.entry("Math").or_insert(100); *num += 2; // iterator hashmap for (k, v) in score { println!("{} : {}", k, v) } } ``` ## Rust中的string和str (string也是容器的一种) 基础概念,对于一个字符串, 有3曾概念 * 计算机存储的是二进制的bytes * 字符编码方式(决定哪些byte组成一个字符),Rust默认是UTF-8编码 * 字符编码后对应的显示字符(最终显示出来的字符串) ``` &str # 可在栈、堆、程序Readonly区, 一般用引用的形式使用, 是对字符串bytes的引用, 可index string # 只会在堆里上, 不可index ``` 常见操作 ``` use unicode_segmentation::UnicodeSegmentation; fn main() { // 初始化方式1 let s1 = "Hello"; let s2 = String::from("World"); println!("{} {}", s1, s2); // 字符串链连接 let s3 = format!("{} {}", &s1, &s2); let s4 = [s1, &s2].concat(); let s5 = concat!("Hello","World"); // only literals (like `"foo"`, `42` and `3.14`) can be passed to `concat!() let s6 = s2 + " World"; // String must be first println!("{}", s6); // 字符串遍历 for i in s6.bytes(){ // 二进制遍历 Bytes println!("{}", i); } for i in s6.chars(){ // 字符遍历 Scaler Value println!("{}", i); } // grapheme cluster add unicode-segmentation = "1.8.0" to dependency for i in s6.graphemes(true) { println!("{}", i); } } ``` ## 模块组织 ## 一些约定 ``` src/lib.rs # 库的入口 src/main.rs # cli 程序入口 ``` ``` src/tests # tests目录为集成测试目录,下面的文件都被当成集成测试对待 src/tests/mod_name/mod.rs # 在 src/tests/xxxx.rs中申明 mon mod_name; 去使用公共库 ``` ## Test ``` #[cfg(test)] mod mytest { #[test] fn test1(){ println!("this is test"); assert_eq!(1,1); } } ``` ``` cargo test -- --show-output #默认test里的print不输出问题 cargo test -- --test-threads=n # 设置测试的线程数 cargo test xxxx # xxxx为前缀匹配的单元测试名字 ``` 如果要ignore掉特定的test,可以加#[ignore]标签 ``` #[test] #[ignore] fn test2(){ println!("this is test"); assert_eq!(1,1); } ```