How to mutate a child of my struct

Hi, just learning Rust this week, so possibly a dumb question: I am trying to write a method on my class to perform some mutation. I have the following setup:

struct Card {
    name: String,
    variant: CardVariant
}
enum CardVariant {
    Unit(Unit),
    Spell
}
enum Unit {
    position: Position
}

I was able to write a method to mutate the name of a Card without any trouble:

fn set_name(card: &mut Card, name: String) {
    card.name = name;
}

But now I am trying to write another method to mutate the child field, and I'm not allowed to:

fn set_position(card: &mut Card, position: Position) {
    match card.variant {
        CardVariant::Unit(u) => u.position = position,
        CardVariant::Spell => (...)
    }
} 

This gives me a "cannot move out of reference" error for card.variant. My beginner understanding of Rust is mostly "you are allowed to mutate things if you use &mut", which seems to not be true here. What is the correct way for me to "look into" my child field and modify it? Thanks!

Fun point is you've already answered your question yourself. You are allowed to mutate things if you use &mut.

fn set_position(card: &mut Card, position: Position) {
    match &mut card.variant {
        CardVariant::Unit(u) => u.position = position,
        CardVariant::Spell => {...}
    }
}

Ah, thanks! I didn't know you had to keep doing &mut.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.