Rust-generic-types

提供:Dev Guides
移動先:案内検索

Rust-ジェネリック型

ジェネリックは、異なるタイプの複数のコンテキストのコードを記述する機能です。 Rustでは、ジェネリックはデータ型と特性のパラメータ化を指します。 Genericsでは、コードの重複を減らし、タイプセーフを提供することで、より簡潔でクリーンなコードを作成できます。 ジェネリックの概念は、メソッド、関数、構造、列挙、コレクション、および特性に適用できます。

typeパラメーターとして知られる _ <T> syntax_ は、汎用構造の宣言に使用されます。 _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() {
  //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()_関数は、構造体の整数インスタンスと文字列インスタンスの2つのインスタンスを作成します。

出力

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
   }
}

トレイトには、具象メソッド(ボディのあるメソッド)または抽象メソッド(ボディのないメソッド)を含めることができます。 メソッド定義がTraitを実装するすべての構造で共有される場合、具体的なメソッドを使用します。 ただし、構造体は、特性によって定義された関数をオーバーライドすることを選択できます。

メソッドの定義が実装構造によって異なる場合は、抽象メソッドを使用します。

構文-特性を実装する

impl some_trait for structure_name {
  //implement method1() there..
   fn method1(&self ){
   }
}

次の例では、構造_book_によって実装されるメソッド_print()_で特性_Printable_を定義しています。

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

汎用関数

この例では、渡されたパラメーターを表示する汎用関数を定義しています。 パラメーターは任意のタイプにすることができます。 パラメータのタイプは、値をprintlnで印刷できるように、表示特性を実装する必要があります! マクロ。

use std::fmt::Display;

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

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 finddevguides