0

I have a struct like this:

struct TeddyBear {
    mood: Option<Box<dyn Mood>>,
}

"Mood" is a trait. Now there are two possible moods: "Happy" and "Sleepy", structs that implement the trait. I've drafted a playground example here.

I'm trying to learn the best way to get the current mood of the teddy-bear at different times in the program.

What I did was to return string values particular to each mood, but it feels somewhat hackish. An enum of values would likely work too, but I would have to remember to add to it each time a new Mood is added. I would like to know if there's a way to use "Happy" or "Sleepy" directly.

Thank you!

carpdan
  • 117
  • 6
  • 2
    you would not have to remember with an enum, if you use `match` with an exhaustive pattern (all cases without a `_`) the compiler will remind you to cover those cases too. Which, imo, is best. – Netwave Jan 22 '22 at 19:25

1 Answers1

0

You could have an enum:

enum MoodKind {
    Happy,
    Sleepy,
}

And a method:

trait Mood {
    fn mood_kind() -> MoodKind;
}

but I would have to remember to add to it each time a new Mood is added.

To avoid implementing this the right way each time, a custom derive attribute has to be used. Rust has no builtin runtime reflection. Refer to this answer as a pointer.

It is not trivial, so think twice about that. Maybe the number of moods is not too big, and you can maintain them manually?

battlmonstr
  • 5,841
  • 1
  • 23
  • 33
  • Thanks for the answer! I'm curious what is the idiomatic approach in Rust for checking the "mood". Using strings was the approach I took, but I'm not particularly happy with it, nor do I believe it's the best approach. – carpdan Jan 26 '22 at 08:40
  • As a side-note, I'm not sure how I would use this in my example. Do you mean to say I should add the `#[derive(Debug)]` to my Happy and Sleepy `struct`s, and remove the `get_mood` method from the trait? How would I get the mood in `main` then? – carpdan Jan 26 '22 at 08:43
  • Yes, if you add #derive to each of your moods, a new method is generated for each of them. In this case that method would return some debug description, and it is possible to get it using `format!("{:?}", mood)`. What do you mean "check the mood"? Do you want methods like `is_happy()`, `is_sleepy()`, or maybe `mood_kind()` returning an enum? Could you update your question to clarify that? – battlmonstr Jan 26 '22 at 10:35
  • I've updated the answer from using strings to using an enum. – battlmonstr Jan 26 '22 at 10:46