Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Anonymous enum in Rust

Tags:

rust

I use this data structure in a project:

#[derive(Serialize, Deserialize)]
pub enum Field {
    last_name(String),
    first_name(String),
    /* etc. */
}

#[derive(Serialize, Deserialize)]
pub struct Update {
    pub id: Id,
    pub field: Field,
}

The enum is not really useful by itself, I use it for deserialization of JSON. So is it possible to do something like that?

#[derive(Serialize, Deserialize)]
pub struct PersonUpdate {
    pub id: Id,
    pub field: enum {
        last_name(String),
        first_name(String),
    }
}
like image 617
Boiethios Avatar asked Feb 26 '17 13:02

Boiethios


People also ask

What is enum in Rust?

An enum in Rust is a type that represents data that is one of several possible variants. Each variant in the enum can optionally have data associated with it: #![allow(unused_variables)] fn main() { enum Message { Quit, ChangeColor(i32, i32, i32), Move { x: i32, y: i32 }, Write(String), }

What is the point of enums in Rust?

Additionally, creating a function that can take any type of Machine as its parameter is not possible using structs; in such a case, enums must be used. With an enum, the type of machine can be identified inside the function by using pattern matching with the match keyword.

How are enums stored in Rust?

All variants of an enum use the same amount of memory (in case of your Foo type, 16 bytes, at least on my machine). The size of the enum's values is determined by its largest variant ( One , in your example). Therefore, the values can be stored in the array directly.

Can enums have methods Rust?

In Rust, methods cannot only be defined on structs, they can also be defined on tuples and enums, and even on built-in types like integers.


1 Answers

It is not possible, you must give it a name, like you did in the first example.

like image 178
Steve Klabnik Avatar answered Nov 03 '22 23:11

Steve Klabnik