Rust 學習筆記
阿新 • • 發佈:2022-05-21
https://doc.rust-lang.org/std/keyword.ref.html
struct, enum
struct 僅僅用來定義一組資料,enum 列舉
struct Human {
name: String,
gender: Gender,
}
enum Gender {
Unknown = 0,
Female = 1,
Male = 2,
}
associated functions and methods
impl Human { fn new() -> Self { Human{name: "hangj".into(), gender: Gender.Male, } } fn test(_i: i32, _j: i32){} }
這種就是 associated function,它的呼叫方式是 Human::new()
Human::test(1, 2)
impl Human {
fn sleep(&self){}
fn eat(&mut self, _food: String){}
}
這種第一個引數是 &self
的函式就是 method,呼叫方式是通過 struct 的例項(instance) 去呼叫
fn main() {
let human = Human::new();
human.sleep();
}
也可以這樣寫 Human::sleep(&human)
&self
和 &mut self
也是個語法糖,其實就是 self: &Human
和 self: &mut Human
Human::sleep(&human)
這種寫法這麼麻煩,什麼時候才有必要這麼寫呢?
當它需要顯式呼叫某個 trait 的同名函式時。
trait 是啥
trait 就類似 C++ 中的純虛擬函式,定義一組介面,是一種約定
trait Animal{ fn noise(&self)-> &'static str; } struct Sheep{} struct Cow{} struct Human{} impl Animal for Sheep { fn noise(&self) -> &'static str {"mieeeeeee"} } impl Animal for Cow { fn noise(&self) -> &'static str {"mooooooo"} } impl Animal for Human { fn noise(&self) -> &'static str {"66666"} } impl Human{ fn noise(&self)-> &'static str{ "hahahah" } } fn main() { let cow = Cow{}; let sheep = Sheep{}; let human = Human{}; println!("{}", cow.noise()); println!("{}", sheep.noise()); println!("{}", human.noise()); println!("{}", Human::noise(&human)); // 與 human.noise() 等效 println!("{}", Animal::noise(&human)); // 顯式呼叫 Animal 的 noise }
generics 範型
fn get_type_name<T>(_v: &T) -> &'static str {
std::any::type_name::<T>()
}
fn main() {
println!("{}", get_type_name(&0));
println!("{}", get_type_name(&("hello".to_string())));
}