Can I create enums in rust that have tuples as values?

Viewed 632

Can I have a tuple as value in enums? Basically I want this in order to use an integer value as a database input and a string value as a friendly response to a UI caller.

For example:

#[derive(Deserialize, Debug)]
enum  MyTestType {
    A(0, "Default"),
    B(1, "something else"),
    C(18, "18"),
    D(4, "D")
}

I am using serde crate in rust and it would be convenient to have it in order to avoid a struct here

1 Answers

Of course:

use serde::Serialize;
use serde_json;

#[derive(Serialize)]
enum Test {
    A(u32, String),   // NOT a tuple
    B((u32, String))  // actual tuple
}

fn main () {
    let a = Test::A(15, "Hello".to_string());
    let b = Test::B((42, "Hi".to_string()));

    println!("{}", serde_json::to_string(&a).unwrap());
    println!("{}", serde_json::to_string(&b).unwrap())
}

Output:

{"A":[15,"Hello"]}
{"B":[42,"Hi"]}
Related