頭條地址:https://www.ixigua.com/i677586170644791348...
B站地址:https://www.bilibili.com/video/av81202308/
1、泛型是具體型別或者其它屬性的抽象替代,用於減少程式碼重複。
2、在函式定義中使用泛型。
例子:
++++++++不使用泛型+++++++++++
//for i32
fn largest_i32(list: &[i32]) -> i32 {
let mut leargest = list[0];
for &item in list.iter() {
if item > largest {
largest = item;
}
}
largest
}
//for char
fn largest_char(list: &[char]) -> char {
let mut leargest = list[0];
for &item in list.iter() {
if item > largest {
largest = item;
}
}
largest
}
fn main(){
let number_list = vec![1, 2, 22, 3, 42];
let r1 = largest_i32(&number_list);
println!("r1 = {}", r1);
let char_list = vec!['a', 'y', 'c', 'd'];
let r2 = largest_char(&char_list);
println!("r2 = {}", r2);
}
//+++++++++使用泛型:會報錯的函式++++++++++++
fn largest<T:PartialOrd + Copy>(list: &[T]) -> T { //注意,要實現比較和複製的trait才行,否則報錯
let mut largest = list[0];
for &item in list.iter() {
if item > largest {
largest = item;
}
}
largest
}
fn main(){
let number_list = vec![1, 2, 22, 3, 42];
let r1 = largest_i32(&number_list);
println!("r1 = {}", r1);
let char_list = vec!['a', 'y', 'c', 'd'];
let r2 = largest_char(&char_list);
println!("r2 = {}", r2);
}
3、在結構體中使用泛型。
例子1:
#[derive(Debug)]
struct Point<T> {
x: T,
y: T,
}
fn main() {
let integer = Point {x: 1, y: 2};
println!("{:#?}", integer);
let float = Point {x: 0.99, y: 1.99};
println!("{:#?}", float);
}
例子2:
#[derive(Debug)]
struct Point<T, U> {
x: T,
y: U,
}
fn main() {
let a = Point {x: 1, y: 2.0};
println!("{:#?}", a);
let b = Point {x: 1, y: 1.99};
println!("{:#?}", b);
}
4、列舉中的泛型
//複習
enum Option<T> {
Some(T),
None,
}
enum Result<T, E> {
Ok(T),
Err(e),
}
5、方法中的泛型
struct Point<T> {
x: T,
y: T,
}
impl<T> Point<T> {
fn get_x(&self) -> &T {
&self.x
}
fn get_y(&self) -> &T {
&self.y
}
}
fn main() {
let p = Point {x: 1, y: 2};
println!("p.x = {}", p.get_x());
println!("p.y = {}", p.get_y());
}
例子2:方法和結構體中使用不同的型別
struct Point<T, U> {
x: T,
y: U,
}
impl<T, U> Point<T, U> {
fn mixup<V, W>(self, other: Point<V, W>) -> Point<T, W> {
Point {
x: self.x,
y: other.y,
}
}
}
fn main() {
let p1 = Point { x: 5, y: 10.4 };
let p2 = Point { x: "Hello", y: 'c'};
let p3 = p1.mixup(p2);
println!("p3.x = {}, p3.y = {}", p3.x, p3.y);
}
6、使用泛型並不會造成程式效能上的損失。rust通過在編譯時進行泛型程式碼的單態化來保證效率。單態化時通過填充編譯時使用的具體型別,將通用程式碼轉換為特定程式碼的過程。
本作品採用《CC 協議》,轉載必須註明作者和本文連結