rust学习笔记(泛型)

  1. 1. 泛型结构体
  2. 2. 结构体方法中的泛型
  3. 3. 为泛型结构体中特定的类型实现方法
  4. 4. 泛型方法

学习内容来自B站:原子之音

泛型结构体

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#[derive(Debug)]
struct Rectangle<T,V> {
width: T,
height: V
}

fn main() {
let res = Rectangle {
width: 7.9f64,
height: 6.7f64
};
println!("{:?}",res);
let res1 = Rectangle {
width: 7u64,
height: 6i64
};
println!("{:?}",res1)
}

1
2
3
4
5
6
cargo run
Finished dev [unoptimized + debuginfo] target(s) in 0.00s
Running `target\debug\exercise.exe`
Rectangle { width: 7.9, height: 6.7 }
Rectangle { width: 7, height: 6 }

结构体方法中的泛型

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#[derive(Debug)]
struct Rectangle<T,V> {
width: T,
height: V
}
impl <T,V> Rectangle<T,V> {
// 两个位置都需要标明泛型
fn get_w(&self) -> &T {
&self.width
// 注意引用
}
}

fn main() {
let res = Rectangle {
width: 7u64,
height: 6.7f64
};
println!("{}",res.get_w())
}

1
2
3
4
5
cargo run
Compiling exercise v0.1.0 (F:\mypro\exercise)
Finished dev [unoptimized + debuginfo] target(s) in 0.32s
Running `target\debug\exercise.exe`
7

为泛型结构体中特定的类型实现方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#[derive(Debug)]
struct Rectangle<T,V> {
width: T,
height: V
}
impl Rectangle<u16,u16> {
fn perimeter(&self) -> u16 {
2*self.width + 2*self.height
}
}

fn main() {
let res = Rectangle {
width: 7u16,
height: 6u16
};
println!("{}",res.perimeter())
}

1
2
3
4
5
cargo run
Compiling exercise v0.1.0 (F:\mypro\exercise)
Finished dev [unoptimized + debuginfo] target(s) in 0.29s
Running `target\debug\exercise.exe`
26

泛型方法

1
2
3
4
5
6
7
8
9
10
11
12
13
fn get_max<T: PartialOrd>(a:T,b:T) -> T {
//此处函数内有比较,故泛型需实现PartialOrd(比较)特质
if a >b {
a
}else {
b
}
}

fn main() {
println!("{}",get_max(12,20))
}

1
2
3
4
5
cargo run
Compiling exercise v0.1.0 (F:\mypro\exercise)
Finished dev [unoptimized + debuginfo] target(s) in 0.31s
Running `target\debug\exercise.exe`
20