Rust - 泛型(Generic)

Rust - 泛型(Generic) 首页 / Rust入门教程 / Rust - 泛型(Generic)

在Rust中,泛型是指数据类型和特征的参数化,泛型可以通过减少代码重复并提供类型安全性来编写更简洁明了的代码。

<T>语法称为类型参数,用于声明泛型构造,T代表任何数据类型。

泛型集合

下面的示例声明一个只能存储整数的向量。

fn main(){
   let mut vector_integer: Vec<i32>=vec![20,30];
   vector_integer.push(40);
   println!("{:?}",vector_integer);
}
[20, 30, 40]

考虑以下片段-

fn main() {
   let mut vector_integer: Vec<i32>=vec![20,30];
   vector_integer.push(40);
   vector_integer.push("hello"); 
   //error[E0308]: mismatched types
   println!("{:?}",vector_integer);
}

上面的示例显示整数类型的向量只能存储整数值,因此,如果我们尝试将字符串值推入集合,则编译器将返回错误。泛型使集合更安全。

泛型结构

type参数表示一种类型,编译器稍后将填充该类型。

struct Data<T> {
   value:T,
}
fn main() {
   //i32 的泛型类型
   let t:Data<i32>=Data{value:350};
   println!("value is :{} ",t.value);
   //String 的泛型类型
   let t2:Data<String>=Data{value:"Tom".to_string()};
   println!("value is :{} ",t2.value);
}

上面的示例声明了一个名为Data的通用结构,<T>类型表示某种数据类型,main()函数创建该结构的两个实例-整数实例和字符串实例。

value is :350
value is :Tom

Traits

特性可以用于实现跨多个结构的一组标准行为(方法),特性类似于面向对象编程中的接口,trait的语法如下所示-

trait some_trait {
   //为空的抽象或方法
   fn method1(&self);
   
   fn method2(&self){
      //method2的一些内容
   }
}

Trait可以包含具体方法或抽象方法,如果方法定义将由实现该Trait的所有结构共享,请使用具体方法。

语法-实现Trait

impl some_trait for structure_name {
   //在那里实现method1()..
   fn method1(&self ){
   }
}

以下示例使用方法 print()定义了特征 Printable ,该方法由结构 book 实现。

无涯教程网

fn main(){
   //创建结构的实例
   let b1=Book {
      id:1001,
      name:"Rust in Action"
   };
   b1.print();
}
//声明一个结构
struct Book {
   name:&'static str',
   id:u32
}
//声明一个特征
trait Printable {
   fn print(&self);
}
//实现特征
impl Printable for Book {
   fn print(&self){
      println!("Printing book with id:{} and name {}",self.id,self.name)
   }
}
Printing book with id:1001 and name Rust in Action

泛型函数

该示例定义了一个通用函数,该函数显示传递给它的参数,该参数可以是任何类型,参数的类型应实现Display trait,以便其值可以由println!宏。

use std::fmt::Display;

fn main(){
   print_pro(10 as u8);
   print_pro(20 as u16);
   print_pro("Hello LearnFKPoint");
}

fn print_pro<T:Display>(t:T){
   println!("Inside print_pro generic function:");
   println!("{}",t);
}
Inside print_pro generic function:
10
Inside print_pro generic function:
20
Inside print_pro generic function:
Hello LearnFKPoint

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

技术与商业案例解读 -〔徐飞〕

如何做好一场技术演讲 -〔极客时间〕

正则表达式入门课 -〔涂伟忠〕

Go 并发编程实战课 -〔晁岳攀(鸟窝)〕

体验设计案例课 -〔炒炒〕

反爬虫兵法演绎20讲 -〔DS Hunter〕

中间件核心技术与实战 -〔丁威〕

大厂设计进阶实战课 -〔小乔〕

手把手带你搭建推荐系统 -〔黄鸿波〕

好记忆不如烂笔头。留下您的足迹吧 :)