Structs, enums e traits

Rust Enums

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

  • Intermediário
  • 3 min de leitura
  • 1 exemplo executável
O que você vai aprender
  • 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.

Pontos-chave

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

Exemplo executável de Rust

Rust
Executar código →
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());
    }
}
Gerar um botão Run para este exemplo Resultado da execução
3.14
7.00
0.00

Pratique

Abra o exemplo no compilador online, mude um valor ou adicione uma linha e tente prever a saída antes de executar. Depois quebre o código de propósito e leia a mensagem do compilador.

Terminou esta lição?

Marque como aprendida para acompanhar seu progresso.

Pratique com um desafio

Use o conteúdo desta lição para resolver um problema real. Cada desafio roda no navegador, com testes instantâneos e uma revisão por IA.

Todos os desafios