CodeBlanks Logo Icon CodeBlanks

Generic enum

Define generic enums like Option<T>.

Generic enums

The two enums you use most are generic:

enum Option<T> {
    Some(T),
    None,
}

enum Result<T, E> {
    Ok(T),
    Err(E),
}

You can write your own generic enum too. For example, to express a search result independent of the type being searched for:

enum Sonuc<T> {
    Bulundu(T),
    Yok,
}

Methods on a generic enum

Methods on a generic enum are also written with impl<T>; the trait bound decides what can be done with the content:

use std::fmt::Display;

impl<T: Display> Sonuc<T> {
    fn goster(&self) -> String {
        match self {
            Sonuc::Bulundu(v) => format!("bulundu: {v}"),
            Sonuc::Yok => String::from("yok"),
        }
    }
}

Practice Search result

Write the Sonuc<T> enum above and the goster method. Print the results for Sonuc::Bulundu(42) and Sonuc::<&str>::Yok separated by | .

Starter code

main.rs
use std::fmt::Display;

fn main() {
    // buraya yaz
}

Sample solution

main.rs
use std::fmt::Display;

enum Sonuc<T> {
    Bulundu(T),
    Yok,
}

impl<T: Display> Sonuc<T> {
    fn goster(&self) -> String {
        match self {
            Sonuc::Bulundu(v) => format!("bulundu: {v}"),
            Sonuc::Yok => String::from("yok"),
        }
    }
}

fn main() {
    let a = Sonuc::Bulundu(42);
    let b = Sonuc::<&str>::Yok;
    println!("{} | {}", a.goster(), b.goster());
}

Expected output

bulundu: 42 | yok

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Why doesn't <code>let s = Sonuc::Yok;</code> compile on its own?

  • Enums can't be generic
  • It compiles
  • T can't be inferred; it must be given like Sonuc::<i32>::Yok Correct answer
  • Yok is an invalid variant

Explanation: The Yok variant carries no information about T; the type is either written explicitly or inferred from later use.

2 Specify the type

Question
let s = Sonuc::____::Yok;
Answer
let s = Sonuc::<i32>::Yok;

Explanation: The turbofish syntax ::<T> gives the type explicitly.

3 Value and type

Term Meaning
Some(5) Option<i32>
Ok::<u8, String>(1) Result<u8, String>
Sonuc::Bulundu("a") Sonuc<&str>
Sonuc::<f64>::Yok Sonuc<f64>

All lessons in Intermediate