[−][src]Derive Macro smart_default::SmartDefault
#[derive(SmartDefault)]
{
// Attributes available to this derive:
#[default]
}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
#[macro_use] extern crate smart_default; #[derive(SmartDefault)] enum Foo { Bar, #[default] Baz { #[default = 12] a: i32, b: i32, #[default(Some(Default::default()))] c: Option<i32>, #[default(_code = "vec![1, 2, 3]")] d: Vec<u32>, #[default = "four"] e: String, }, Qux(i32), } assert!(Foo::default() == Foo::Baz { a: 12, b: 0, c: Some(0), d: vec![1, 2, 3], e: "four".to_owned(), });
Bazhas the#[default]attribute. This means that the defaultFoois aFoo::Baz. Only one variant may have a#[default]attribute, and that attribute must have no value.ahas a#[default = 12]attribute. This means that it's default value is12.bhas no#[default = ...]attribute. It's default value willi32's default value instead -0.cis anOption<i32>, and it's default isSome(Default::default()). Rust cannot (currently) parse#[default = Some(Default::default())]and therefore we have to use a special syntax:#[default(Some(Default::default))]dhas the!token in it, which cannot (currently) be parsed even with#[default(...)], so we have to encode it as a string and mark it as_code =.eis aString, so the string literal "four" is automatically converted to it. This automatic conversion only happens to string (or byte string) literals - and only if_codeis not used.- Documentation for the
impl Defaultsection is generated automatically, specifying the default value returned from::default().