Rust Note(11)_trait

trait 特質介紹


特質/特性 : 這個是一個抽象的接口。
來接續上篇所說的抽象層的概念。

上一篇提到的抽象層 Abstract layer 的概念
可以參閱 Rust Note(10)

共同特性的特性集合起來,放在一個共同的地方,
讓有共同特性的物件 objects 可以透過呼叫這個接口,
來直接套用特性,避免重複撰寫

struct 例子 (1 vs 1)

前篇我們使用的是 struct 結構體,利用結構體把擁有共通特性的結構整併起來。

然後使用 impl implementation 來實作 struct,使其有專屬的 function!!!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
struct User {
user_name: String,
user_mail: String,
}

impl User {
fn user_info(&self) {
println!("User name: {} User mail:{}", self.user_name, self.user_mail)
}
}

fn main() {
let user_1 = User {
user_name: String::from("Kylls KB"),
user_mail: String::from("kylls.ccs@gmail.com")
};

user_1.user_info();

}
// output : User name: Kylls KB User mail: kylls.ccs@gmail.com

以上是使用struct的例子

接著介紹另外一個方法trait

trait 例子 (1 vs 2?3?…or more…)


struct 用的是建構出共通的結構子 constructor
imp 是使用於實作方法(使用&self 呼叫建構子)
一個struct >> 一個impl ……..
那如果多個struct 呢???
那還不狂寫一波?

真的假的

設計語言的利用抽象化的 trait
能夠越簡化代碼,就能夠減少重複撰寫,減少人為疏失

On the other words, simple is good.
就是越簡單&&越清楚越好!!!

行為抽象化

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
struct People {
name: String,
age: u64,
}

// 建立方法抽象層
trait Action {
// function do 返回不指定,可自定義
fn say_hello(&self);
// function can_do 返回 true or false
fn can_do(&self) -> bool;
}

// 實作方法 by using trait for struct
// 同樣性質的trait, 可以用來實作多個結構體,
// 使用 `for` -> 專屬哪個struct
impl Action for People {
// &self 使用自己的意思
fn say_hello(&self) {
println!("Hello, my name is {}.", self.name)
}

// 注意返回是boolean
fn can_do(&self) -> bool {
if self.age < 50 {
return true
} else {
return false
}
}
}

fn main() {
let people_1 = People {
// new 一個新的String出來
name: String::from("Kylls"),
age: 18,
};

println!("Can {} speak? {}", people_1.name, people_1.can_do());
// output: Can Kylls speak? true
people_1.say_hello();
// output: Hello, my name is Kylls.

}

描述擁有的共同架構,集合成struct
描述相同行為的動作,集合成trait

更進一步的敘述出 物件會有的行為特質

Rust Note_20211122