How to do this?

I have been stuck with an excercise for a couple of hours: The starter code contains an enum that needs a Default trait implementation so that a struct containing it as a field can derive the Default trait.

Derive the trait Default for the enum in the starter code. The compiler will help you here also. Starter code: #[derive(Debug, PartialEq, Eq)]
enum Status {
Online,
Offline,
}

#[derive(Debug, Default)]
struct User {
name: String,
status: Status,
}

fn main() {
let user = User::default();
println!("{:?}", user);
}

you can try what the problem hinted:

#[derive(Debug, Default, PartialEq, Eq)]
enum Status {
    Online,
    Offline,
}

the compiler will tell you:

error: no default declared
 --> src/lib.rs:1:17
  |
1 | #[derive(Debug, Default, PartialEq, Eq)]
  |                 ^^^^^^^
  |
  = help: make a unit variant default by placing `#[default]` above it

you just do what the compiler tells you: add a #[default] attribute

#[derive(Debug, Default, PartialEq, Eq)]
enum Status {
    #[default]
    Online,
    Offline,
}

the compiler is very helpful, just try to learn from it.

5 Likes