ddg
ddg

Reputation: 1098

Problems Initialize Rust Struct

Making a card game to learn Rust. Having trouble initializing my struct.

enum Effect {
    Passive,
    EarnEffect,
    ChargeEffect,
}

struct EarnEffect {
    amount: i8,
    per: Option<Tag>,
}

struct Card {
    effect: Effect
}

Have already tried the following:

Card { effect: Effect::EarnEffect { amount: 1, per: None }}

and

Card { effect: EarnEffect { amount: 1, per: None }}

Upvotes: 0

Views: 97

Answers (1)

loganfsmyth
loganfsmyth

Reputation: 161447

Your enum variant and your struct are two separate entities, even though you've given them the same name.

enum Effect {
    Passive,
    EarnEffect,
    ChargeEffect,
}

explicitly means that the enum can have exactly 3 possible values, with no additional data. You can associate data with an enum variable with either

enum Effect {
    Passive,
    // Struct-like syntax
    EarnEffect {
      amount: i8,
      // ...
    },
    ChargeEffect,
}

or

enum Effect {
    Passive,
    // Tuple-like syntax
    EarnEffect(i8),
    ChargeEffect,
}

You'll need to either use a enum struct variant, or put your struct as the data of a tuple variant. Currently you have things mismatched.

Option 1

enum Effect {
    Passive,
    EarnEffect {
        amount: i8,
        per: Option<Tag>,
    },
    ChargeEffect,
}

struct Card {
    effect: Effect
}

with

Card { effect: Effect::EarnEffect { amount: 1, per: None }}

Option 2

enum Effect {
    Passive,
    EarnEffect(EarnEffect),
    ChargeEffect,
}

struct EarnEffect {
    amount: i8,
    per: Option<Tag>,
}

struct Card {
    effect: Effect
}

with

Card { effect: Effect::EarnEffect(EarnEffect { amount: 1, per: None }) }

Upvotes: 4

Related Questions