構造体、列挙型、トレイト

Rust Enums

A type that is exactly one of several variants, where each variant can carry its own data.

  • 中級
  • 約3分で読めます
  • 実行できるサンプル 1 件
学べること
  • Variants with data
  • match on an enum
  • Methods on enums
enum Shape
  • Shape
    • Circle(f64)
    • Rectangle { width, height }
    • Point

One of several shapes

An enum is a type whose value is exactly one of a fixed list of variants. In Rust each variant can carry its own data, so one enum can describe several different shapes of information.

Circle carries one number, Rectangle carries two named fields and Point carries nothing. match must handle every variant, so the compiler reports an error if you add a variant and forget a case. {:.2} prints two digits after the decimal point.

重要なポイント

  1. Each variant can hold different data.
  2. match must cover every variant.
  3. Forgetting one is a compile error.

実行できる Rust のサンプル

Rust
コードを実行 →
main.rs
enum Shape {
    Circle(f64),
    Rectangle { width: f64, height: f64 },
    Point,
}

impl Shape {
    fn area(&self) -> f64 {
        match self {
            Shape::Circle(radius) => 3.14159 * radius * radius,
            Shape::Rectangle { width, height } => width * height,
            Shape::Point => 0.0,
        }
    }
}

fn main() {
    let shapes = [
        Shape::Circle(1.0),
        Shape::Rectangle { width: 2.0, height: 3.5 },
        Shape::Point,
    ];
    for shape in &shapes {
        println!("{:.2}", shape.area());
    }
}
この例の実行ボタンを作成 実行結果
3.14
7.00
0.00

練習

サンプルをオンラインコンパイラーで開き、値を変えたり行を追加したりして、実行する前に出力を予想してみましょう。次に、わざとコードを壊してコンパイラーのメッセージを読んでみてください。

このレッスンを終えましたか?

学習済みにすると進み具合を記録できます。

チャレンジで練習する

このレッスンの内容を使って実際の問題を解きましょう。各チャレンジはブラウザで動き、すぐにテストされ、AI のレビューも受けられます。

すべてのチャレンジ