`#[derive(Default)]` for enum, non only struct

The Default macro is a compiler builtin. Currently we can #[derive(Default)] for structs but not for enums. I wonder if somebody else would like to have the ability to #[derive(Default)] for enums in std.

Through when #[derive(Default)] for structs, struct fields can only be
the default value of the field type and cannot be customized with optional value.
What I am proposing is to add the #[default] attribute to enums.
The enum variant with #[default] label cannot be customized like structs fields.

  • Field-less enums:

    #[derive(Default)]
    pub enum E {
      #[default]
      A,
      B,
    }
    assert_eq!(E::default(), E::A);
    
  • Struct field enums:

    #[derive(Default)]
    pub enum E {
      A,
      #[default]
      B {
        a: i32,
        b: String
      }
    }
    assert_eq!(E::default(), E::B { a: 0, b: "".to_string() });
    
  • Tuple-like enums:

    #[derive(Default)]
    pub enum E {
      #[default]
      A(i32, String),
      B,
    }
    assert_eq!(E::default(), E::A(0, "".to_string()));
    

You can manually implement Default like this:

enum Kind {
    A,
    B,
    C,
}

impl Default for Kind {
    fn default() -> Self { Kind::A }
}

See also this thread.

3 Likes

Thanks. I've already known how to implement the Default trait. The manually code
to implement Default is not too long. But I find the inconsistence that
structs can be #[derive(Default)] but enums cannot.

This part has been added to the first post.

Well, there is an obvious default for structs, and there isn't for enums, so I do not think that this is inconsistent.

1 Like

Please do a little searching before asking questions. This was asked not 7 hrs ago and got an answer only 5 hrs ago.

1 Like

I read it before this thread. What I proposed is the std support, which not belongs to external crates.

2 Likes

You should open an internals thread instead.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.