当前位置:   article > 正文

学习Rust的第16天:泛型类型

学习Rust的第16天:泛型类型

泛型类型是减少代码重复的好方法,因此它们对性能有巨大的影响,通过利用Rust中的泛型类型,开发人员可以编写更通用和可重用的代码,同时保持类型安全和性能。这种方法不仅减少了冗余,还增强了代码的可维护性和可扩展性,还可以促进更清晰、更灵活的设计,使开发人员能够轻松地适应不断变化的需求。

Introduction 介绍

Generic types in Rust allow you to write functions, structs, and enums that can operate on multiple data types without sacrificing type safety, enabling code reuse and flexibility. Let’s take a look at a use case.
Rust中的泛型类型允许您编写可以对多种数据类型进行操作的函数,结构和枚举,而不会牺牲类型安全性,从而实现代码重用和灵活性。让我们来看看一个用例。

  1. fn find_max(x: i32, y: i32) -> i32{
  2. if x > y {
  3. x
  4. }else{
  5. y
  6. }
  7. }
  8. fn main(){
  9. let result: i32 = find_max(9,10);
  10. println!("The maximum value is : {}", result);
  11. }

Output: 输出量:

The maximum value is 10

If I wanted to use the same function for characters or floating point numbers, I would have to create a new function with the specific types with basically the same logic. Generic type helps to reduce this code duplication.
如果我想对字符或浮点数使用相同的函数,我必须创建一个具有基本相同逻辑的特定类型的新函数。泛型类型有助于减少这种代码重复。

We can declare multiple generic types for a function/struct. Single generic types are generally denoted by T which stands for Type.
我们可以为一个函数/结构声明多个泛型类型。单个泛型类型通常用 T 表示,它代表 Type 。

Generic types are declare within <> in a function.
泛型类型在函数中的 <> 中声明。

Example : 范例:

  1. fn find_max<T: PartialOrd>(x: T, y: T) -> T {
  2. if x > y {
  3. x
  4. } else {
  5. y
  6. }
  7. }
  8. fn main() {
  9. let result = find_max(10, 5);
  10. println!("The maximum value is: {}", result);
  11. let result_float = find_max(4.5, 3.2);
  12. println!("The maximum value is: {}", result_float);
  13. let result_char = find_max('x','a');
  14. println!("The maximum value is: {}", result
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/码创造者/article/detail/951233
推荐阅读
相关标签
  

闽ICP备14008679号