Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I access enum fields directly?

Tags:

enums

rust

I'm just learning Rust. So I know this works:

enum Animal {
    Cat { name: String, weight: f64 }
}

fn main() {
    let a = Animal::Cat { name: "Spotty".to_string(), weight: 2.7 };
    match a {
        Animal::Cat{name, weight} => { println!("Cat n={} w={}", name, weight); }
    }
}

but why can I not assign from an enum field directly like this:

    ...
    let wt = a.weight;

Or am I using the wrong syntax? Or is it because Rust cannot guarantee an Animal instance will be of type Cat? Is the only way to access fields of an instance of enum struct or tuple variant by using match?

like image 553
eplictical Avatar asked Oct 23 '25 13:10

eplictical


2 Answers

It is because weight isn't part of the Animal enum, it's part of the Cat type of the enum. Say in the future you add another type of animal that doesn't have weight information:

enum Animal {
    Cat { name: String, weight: f64 },
    Insect { species: String, height: f64 },
}

Then a.weight wouldn't always have a value. You can use if let or match to conditionally get data from an enum if it exists:

if let Animal::Cat { weight, .. } = a {
    println!("Your cat weights {} kg.", weight);
} else {
    println!("get a cat");
};
like image 153
Smitop Avatar answered Oct 25 '25 16:10

Smitop


Or is it because Rust cannot guarantee an Animal instance will be of type Cat?

Yes. In a normal enum, you'd have multiple variants, which may or may not have the same types, and thus fields (in fact some may not have fields at all).

So while it would technically be possible for rust to have attribute access on enums with a single variant or where all variants have a compatible version of the attribute, those are such rare cases they don't really matter and the value of such complexity would be essentially nil.

I don't rightly see the point of using a single-variant enum tho, why are you not just using a struct?

struct Cat { name: String, weight: f64 }

?

Is the only way to access fields of an instance of enum struct or tuple variant by using match?

You could also use an if let though that's essentially the same. Or you can have a method which exposes the information (with a match or if let inside), as convenience (or because the variants are private).

like image 25
Masklinn Avatar answered Oct 25 '25 15:10

Masklinn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!