How to define Rust enums with associated data in your candid file?

How to define Rust enums with associated data in your candid file:

I have a struct that looks like this

struct Member {
    pub principal_id: Principal,
    pub name: String,
}

and a enum that looks like this:

enum ProposalType {
    AddMember(Member),
    Foo,
    Bar,
    ...
}

How would I define the ProposalType enum in my .did file?

Hey, this worked for me:

In rust:

#[derive(Clone, Debug, CandidType, Deserialize)]
enum GameState {
    New,
    Asked,
    Answered,
}

#[derive(Clone, Debug, Default, CandidType, Deserialize)]
struct Game {
    pub id: u32,
    [...]
    pub state: GameState,
}

And in candid I have it like so:

type GameState = variant {
    New;
    Asked;
    Answered;
};

type Game = record {
    "id": nat32;
    [...]
    "state": GameState;
};

2 Likes

Hey GLdev,

Thanks for the answer! I think my situation is a bit different though. You use an enum in your struct while I use a struct in my enum. Nonetheless in the end it seemed to work the same.

and I just had to to:

type ProposalType = variant {
    AddMember: Member;
    Foo,
    Bar
};

The reason it went wrong is because of using wrong names :sweat:

1 Like