📝

ジェネリクス

に公開

ジェネリクスとは

どの型にもなれる変数という認識です。(私は)

関数定義において

fn test<T>(x: [&T]) -> T {
}

構造体において

Tを同じにすると同じ型しか使えない。

struct Point<T> { // コンパイルエラー‼
    x: T,
    y: T,
}
struct Point<T, U> { // Gooooooooood
    x: T,
    y: U,
}
fn main() {
    let wont_work = Point { x: 5, y: 4.0 }; 
}

メソッド定義において

struct Point<T, U> {
    x: T,
    y: U,
}

impl<T, U> Point<T, U> {
    fn mixup<V, W>(self, other: Point<V, W>) -> Point<T, W> {
        Point {
            x: self.x,
            y: other.y,
        }
    }
}

fn main() {
    let p1 = Point { x: 5, y: 10.4 };
    let p2 = Point { x: "Hello", y: 'c'};

    let p3 = p1.mixup(p2);

    println!("p3.x = {}, p3.y = {}", p3.x, p3.y);
}

コードのパフォーマンスについて

ジェネリックな型を利用することで、コンパイルのスピードは少し落ちるが、実行速度は下がらないようになっている。なんなら速いらしいです。

Option<T>{
    Some(T),
    None,
}
let integer = Some(5);
let float = Some(5.0);

このコードをコンパイルすると・・・

enum Option_i32 {
    Some(i32),
    None,
}

enum Option_f64 {
    Some(f64),
    None,
}

fn main() {
    let integer = Option_i32::Some(5);
    let float = Option_f64::Some(5.0);
}

こうなる。

Discussion