核心概念
泛型
泛型是一种编程语言的特性,它允许在代码中使用参数化类型,以便在不同地方使用相同的代码逻辑处理多种数据类型,而无需为每种类型编写单独的代码!
作用:
- 提高代码的重复性
- 提高代码的可读性
- 提高代码的抽象度
泛型的应用类型:
- 泛型定义结构体/枚举
- 泛型定义函数
- 泛型与特质
Generic Structure Definition
1#[derive(Debug)]2struct Point<T> {3 x: T,4 y: T,5}67#[derive(Debug)]8struct PointTwo<T, E> {9 x: T,10 y: E,11}1213fn main() {14 let c1 = Point {x: 1.0, y: 2.0};15 let c2 = Point {x:'x', y: 'y'};16 println!("c1 {:?} c2 {:?}", c1, c2); // c1 Point {x: 1.0, y: 2.0} c2 Point {x: 'x', y: 'y'}17 let c = PointTwo {x: 1.0, y: 'z'};18 println!("{:?}", c); // PointTwo {x: 1.0, y: 'z'}19 // 零成本抽象20}
Generics & Functions
在Rust中,泛型也可以用于函数,使得函数能够处理多种类型的参数,提高代码的重用性和灵活性。
- 泛型与函数
- 泛型与结构体中的方法
例子:
1// 交换2fn swap<T>(a: T, b: T) -> (T, T) {3 (b, a)4}56struct Point<T> {7 x: T,8 y: T,9}1011impl<T> Point<T> {12 fn new(x: T, y: T) -> Self {13 Point{x, y}14 }1516 // 方法, 加引用是为了防止当T是String的时候,返回以后所有权丢失17 fn get_coordinates(&self) -> (&T, &T) {18 (&self.x, &self.y)19 }20}21fn main() {22 let result = swap(0, 1);23 println!("{:?}", result); // (1, 0)2425 let str2 = swap("hh", "tt");26 println!("str2.0 {} str2.1 {}", str2.0, str2.1); // str2.0 tt str2.1 hh27 let str2 = swap(str2.0, str2.1);28 println!("str2.0 {} str2.1 {}", str2.0, str2.1); // str2.0 hh str2.1 tt2930 let i32_point = Point::new(2, 3);31 let f64_point = Point::new(2.0, 3.0);32 let (x1, y1) = i32_point.get_coordinates();33 let (x2, y2) = f64_point.get_coordinates();34 println!("i32 point: x={} y={}", x1, y1);35 println!("f64 point: x={} y={}", x2, y2);3637 // 最好用String, 不用&str38 let string_point = Point::new("x".to_owned(), "y".to_owned());39 println!("string point x={} y={}", string_point.x, string_point.y);4041}