- Rust 教程
- Rust - 首页
- Rust - 简介
- Rust - 环境搭建
- Rust - HelloWorld 例子
- Rust - 数据类型
- Rust - 变量
- Rust - 常量
- Rust - 字符串
- Rust - 运算符
- Rust - 决策
- Rust - 循环
- Rust - 函数
- Rust - 元组
- Rust - 数组
- Rust - 所有权
- Rust - 借用
- Rust - 切片
- Rust - 结构体
- Rust - 枚举
- Rust - 模块
- Rust - 集合
- Rust - 错误处理
- Rust - 泛型类型
- Rust - 输入输出
- Rust - 文件输入/输出
- Rust - 包管理器
- Rust - 迭代器和闭包
- Rust - 智能指针
- Rust - 并发
- Rust 有用资源
- Rust - 快速指南
- Rust - 有用资源
- Rust - 讨论
Rust - 泛型类型
泛型是编写适用于多种不同类型上下文的代码的一种机制。在 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);
}
以上示例表明,整数类型的向量只能存储整数值。因此,如果尝试将字符串值推入集合,编译器将返回错误。泛型使集合更具类型安全。
示例:泛型结构体
类型参数代表一个类型,编译器稍后将填充该类型。
struct Data<T> {
value:T,
}
fn main() {
//generic type of i32
let t:Data<i32> = Data{value:350};
println!("value is :{} ",t.value);
//generic type of String
let t2:Data<String> = Data{value:"Tom".to_string()};
println!("value is :{} ",t2.value);
}
以上示例声明了一个名为Data的泛型结构体。<T>类型指示某种数据类型。main()函数创建了两个实例——结构体的整数实例和字符串实例。
输出
value is :350 value is :Tom
特征
特征可用于在多个结构体中实现一组标准的行为(方法)。特征就像面向对象编程中的接口。特征的语法如下所示:
声明一个特征
trait some_trait {
//abstract or method which is empty
fn method1(&self);
// this is already implemented , this is free
fn method2(&self){
//some contents of method2
}
}
特征可以包含具体方法(带有方法体的方法)或抽象方法(没有方法体的方法)。如果所有实现该特征的结构体都将共享方法定义,则使用具体方法。但是,结构体可以选择覆盖特征定义的函数。
如果实现结构体的方法定义有所不同,则使用抽象方法。
语法 - 实现一个特征
impl some_trait for structure_name {
// implement method1() there..
fn method1(&self ){
}
}
以下示例定义了一个具有print()方法的Printable特征,该方法由book结构体实现。
fn main(){
//create an instance of the structure
let b1 = Book {
id:1001,
name:"Rust in Action"
};
b1.print();
}
//declare a structure
struct Book {
name:&'static str,
id:u32
}
//declare a trait
trait Printable {
fn print(&self);
}
//implement the trait
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 特征,以便其值可以通过 println! 宏打印。
use std::fmt::Display;
fn main(){
print_pro(10 as u8);
print_pro(20 as u16);
print_pro("Hello TutorialsPoint");
}
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 TutorialsPoint
广告