Crate smart_default [] [src]

Smart Default

This crate provides a custom derive for SmartDefault. SmartDefault is not a real type - deriving it will actually impl Default. The difference from regular #[derive(Default)] is that #[derive(SmartDefault)] allows you to use #[default = "..."] attributes to customize the ::default() method and to support structs that don't have Default for all their fields - and even enums!

Examples


#[derive(SmartDefault)]
enum Foo {
    Bar,
    #[default]
    Baz {
        #[default = "12"]
        a: i32,
        b: i32,
        #[default = r#""hello""#]
        c: &'static str,
    },
    Qux(i32),
}

assert!(Foo::default() == Foo::Baz { a: 12, b: 0, c: "hello" });
  • Baz has the #[default] attribute. This means that the default Foo is a Foo::Baz. Only one variant may have #[default], and it must have no value.
  • a has a #[default = "12"] attribute. This means that it's default value is 12. Currently custom attributes can only be strings, so the default value must be encoded in a string as well.
  • b has no #[default = "..."] attribute. It's default value will i32's default value instead - 0.
  • c is a string, and thus it's default value - a string - must be escaped inside that attribute. You can't use #[default = "hello"] here - that will look for a constant named hello and use it's value as c's default.