RUST-the book 7、8章 ---- [TOC] ---- source https://doc.rust-lang.org/book/ch07-00-managing-growing-projects-with-packages-crates-and-modules.html --- # chapter 7 ### 模組管理 大型專案的RUST如何管理library、檔案結構? ---- ### 本章重點 * Packages: A Cargo feature that lets you build, test, share crates * Crates: A tree of modules that produces a library or executable * Modules and use: Let you control the organization, scope, and privacy * Paths: A way of naming an item --- # 7.1 crate ---- ### crate > A crate is the smallest amount of code that the Rust compiler considers at a time ##### 執行單一rust script時,compile 考慮該檔案是個crate ---- ### crate有2種 1. binary crate programs you can compile to an executable that you can run e.g. command-line program、server src /main.py 2. library crate they don’t compile to an executable. Instead, they define functionality intended to be shared with multiple projects e.g. rand crate provide the functionality that generate random numbers src /lib.rs ---- ## 實作時間 ```rust cargo new my-project ``` --- # 7.2 module ---- ## modules namely paths that allow you to name items; 1. the use keyword that brings a path into scope; 2. the pub keyword to make items public ---- ## how module work(1)? 1. Start from the crate root: When compiling a crate, the compiler first looks in the crate root file (usually src/lib.rs for a library crate or src/main.rs for a binary crate) for code to compile. ---- ## how module work(2)? 2. Declaring modules: In the crate root file, you can declare new modules; say, you declare a “garden” module with mod garden;. The compiler will look for the module’s code in these places: * Inline, within curly brackets that replace the semicolon following mod garden * In the file src/garden.rs * In the file src/garden/mod.rs ---- ## how module work(3)? 3. Declaring submodules: In any file other than the crate root, you can declare submodules. For example, you might declare mod vegetables; in src/garden.rs. The compiler will look for the submodule’s code within the directory named for the parent module in these places: * Inline, directly following mod vegetables, within curly brackets instead of the semicolon * In the file src/garden/vegetables.rs * In the file src/garden/vegetables/mod.rs ---- ## how module work(4)? 4. Paths to code in modules: Once a module is part of your crate, you can refer to code in that module from anywhere else in that same crate e.g. crate::garden::vegetables::Asparagus. ---- ## how module work(5)? 5. Private vs public: 6Code within a module is private from its parent modules by default. To make a module public, declare it with pub mod instead of mod. mod dateTool<- 預設是private pub mod dateTool <- 使mod變public ---- ## how module work(6)? 6. The use keyword: Within a scope, the use keyword creates shortcuts to items to reduce repetition of long paths. 原: crate::garden::vegetables::Asparagus 使用use: use crate::garden::vegetables::Asparagus ---- ## 實作時間 ```rust use crate::garden::vegetables::Asparagus; pub mod garden; fn main() { let plant = Asparagus {}; println!("I'm growing {:?}!", plant); } ``` --- # 7.3 paths ---- ```rust // Absolute path crate::front_of_house::hosting::add_to_waitlist(); // Relative path front_of_house::hosting::add_to_waitlist(); ``` :::info 記得要export給別人用的要設pub ::: ---- :::success best practice best practice ##### package can contain both src/main.rs and src/lib.rs 1. module.tree 放 lib.rs 2. binary crate(main/rs)成為lib的user(pub物件的user) ::: ---- ## 實作時間 ```rust // super fn deliver_order() {} mod back_of_house { fn fix_incorrect_order() { cook_order(); // similar to .. super::deliver_order(); } fn cook_order() {} } ``` --- # 7.4 bring path to scope with use ---- ## use :::info ::: :::info 1. use 也有scope 2. 避免撞名 1. 把parent整個搬進來 2. as 3. reexport ::: ```rust= use std::fmt; use std::io; fn function1() -> fmt::Result { // --snip-- } fn function2() -> io::Result<()> { // --snip-- } ``` ---- ## use external package e.g. rand ```rust use rand::Rng; fn main() { let mut rng = rand::thread_rng(); let random_number = rng.gen_range(1..101); println!("Random number: {}", random_number); } ``` ---- :::info nested path use std::{cmp::Ordering, io}; ::: :::info glob operator use std::collections::*; ::: --- # 7.5 sepearate module to different file ---- ### 實戰時間 --- # chapter 8 common collections * Vectors * String * HashMap --- # 8.1 Vectors ---- ```rust let v: Vec<i32> = Vec::new(); let v = vec![1, 2, 3]; // rust will auto infer let mut v = Vec::new(); v.push(5); v.push(6); v.push(7); v.push(8); let third: &i32 = &v[2]; <- 不存在會panic println!("The third element is {third}"); let third: Option<&i32> = v.get(2); <- 回傳None若不存在 ``` ---- # 8.2 Strings ---- 複習 &str vs String (no gb , scope(ownership), ref, mut) ---- 常用String 方法 :::info String::from "apple".toString ::: ---- :::warning Strings Are Not So Simple😢 ::: 1. can't use index to access char(因為不同字編碼出的長度不同) --- # 8.3 Hash Maps ---- rust最類似 js object , python dict的存在 (by chatGpt) ```rust use std::collections::HashMap; 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 = scores.get(&team_name).copied().unwrap_or(0); ``` --- 謝謝收看 ---
{"metaMigratedAt":"2023-06-18T01:00:17.984Z","metaMigratedFrom":"YAML","title":"chapter 7","breaks":true,"slideOptions":"{\"transition\":\"slide\",\"spotlight\":{\"enabled\":true}}","contributors":"[{\"id\":\"fd8753d8-d3f1-42d1-9d9c-3068882df242\",\"add\":13118,\"del\":7405}]"}
    223 views