2

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

malefstro
  • 149
  • 9

1 Answers1

2

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"]}
ForceBru
  • 43,482
  • 10
  • 63
  • 98
  • 1
    Actually I was asking if it possible to define the enumerators (A,B,..) with constant values – malefstro May 06 '20 at 12:28
  • @malefstro, https://stackoverflow.com/questions/36928569/enums-with-constant-values-in-rust – ForceBru May 06 '20 at 12:32
  • @malefstro, looks like you can only use integers like that, though. [Tuples don't seem to work](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=9cdc7430b6b3a0afdad7e5a4295524cc) – ForceBru May 06 '20 at 12:39
  • so that value function will return a the tuple? – malefstro May 06 '20 at 12:58
  • @malefstro, yes. `enum MyTestType { A(0, "Default"), B(1, "something else") }` is invalid, though( – ForceBru May 06 '20 at 13:01