泛型可以使用在结构体中
- struct Pair<T> {
- x: T,
- y: T,
- }
其中 x,y 都属于 T 类型.
实现结构体的方法或者关联函数需要在 impl 关键字后面指定泛型
- impl<T> Pair<T> {
- fn new(x: T, y: T) -> Self {
- Self {
- x,
- y,
- }
- }
- }
- impl<T> Point<T> {
- fn x(&self) -> &T {
- &self.x
- }
- }
讲到泛型就绕不开 trait,trait 类似于其他语言中的接口
具体使用方法如下
- pub trait Summarizable {
- fn summary(&self) -> String;
- }
- pub struct NewsArticle {
- pub headline: String,
- pub location: String,
- pub author: String,
- pub content: String,
- }
- impl Summarizable for NewsArticle {
- fn summary(&self) -> String {
- format!("{}, by {} ({})", self.headline, self.author, self.location)
- }
- }
要希望泛型拥有特定的功能, 就必须指定泛型的 trait, 简称 trait bound
- impl<T: Display + PartialOrd> Pair<T> {
- fn cmp_display(&self) {
- if self.x>= self.y {
- println!("The largest member is x = {}", self.x);
- } else {
- println!("The largest member is y = {}", self.y);
- }
- }
- }
泛型 T 要有比较和打印功能, 就要指定 T 的 trait bound
有一个易于观看的 trait bound 语法
- fn some_function<T, U>(t: T, u: U) -> i32
- where T: Display + Clone,
- U: Clone + Debug
- {
- }
也可以这样写
- fn some_function<T: Display + Clone, U: Clone + Debug>(t: T, u: U) -> i32 {
- }
- impl<T> Point<T> {
- fnx(&self) -> &T {
- &self.x
- }
- }
来源: https://www.cnblogs.com/kwebi/p/9462132.html