1. 程式人生 > 其它 >Rust 學習筆記

Rust 學習筆記

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)

, 其實本質上,呼叫方式跟 associated function 並無區別, 只不過是語言層面提供的語法糖(syntax sugar)
&self&mut self 也是個語法糖,其實就是 self: &Humanself: &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())));
}

derive