core_extensions/macros/
const_default.rs

1/// Gets the [`ConstDefault::DEFAULT`](trait.ConstDefault.html#associatedconstant.DEFAULT)
2/// associated constant for a type.
3/// 
4/// Use this macro to avoid accidentally using inherent `DEFAULT` associated cosntants.
5/// 
6/// # Argument
7/// 
8/// If a type is passed (ie: `const_default!(Foo)`),
9/// this gets its [`ConstDefault::DEFAULT`] associated constant.
10/// 
11/// If nothing is passed (ie: `const_default!()`),
12/// this is equivalent to [`ConstDefault::DEFAULT`],
13/// inferring the type it gets the default value of.
14/// 
15/// # Examples
16/// 
17/// ### Basic
18/// 
19/// ```rust
20/// use core_extensions::const_default;
21/// 
22/// assert_eq!(const_default!(u32), 0);
23/// assert_eq!(const_default!(bool), false);
24/// assert_eq!(const_default!((bool, Option<u32>)), (false, None));
25#[cfg_attr(
26    feature = "alloc",
27    doc = "assert_eq!(const_default!(([u32; 0], Vec<u32>)), ([], Vec::new()));"
28)]
29/// 
30/// let list: &[u8] = const_default!();
31/// assert!(list.is_empty());
32/// 
33/// let string: &str = const_default!();
34/// assert!(string.is_empty());
35/// 
36/// ```
37/// 
38/// ### Implementing `ConstDefault`
39/// 
40/// ```rust
41/// use core_extensions::{ConstDefault, const_default};
42/// 
43/// #[derive(Debug, PartialEq)]
44/// struct Foo<T> {
45///     foo: u32,
46///     bar: Option<T>,
47/// }
48/// 
49/// impl<T> ConstDefault for Foo<T> {
50///     const DEFAULT: Self = Self {
51///         foo: const_default!(),
52///         bar: const_default!(),
53///     };
54/// }
55/// 
56/// let expected = Foo{foo: 0, bar: None};
57/// assert_eq!(const_default!(Foo<u32>), expected);
58/// assert_eq!(Foo::<u32>::DEFAULT, expected);
59/// 
60/// 
61/// ```
62/// 
63/// ### Inherent `DEFAULT` associated constant
64/// 
65/// This demonstrates how inherent associated constants have priority over 
66/// trait associated constants.
67/// 
68/// ```rust
69/// use core_extensions::{ConstDefault, const_default};
70/// 
71/// #[derive(Debug, PartialEq)]
72/// struct Foo(u32);
73/// 
74/// impl ConstDefault for Foo {
75///     const DEFAULT: Self = Foo(0);
76/// }
77/// 
78/// impl Foo {
79///     const DEFAULT: Self = Foo(3333);
80/// }
81/// 
82/// assert_eq!(const_default!(Foo), Foo(0));
83/// assert_eq!(<Foo as ConstDefault>::DEFAULT, Foo(0));
84/// assert_eq!(Foo::DEFAULT, Foo(3333));
85/// 
86/// ```
87/// 
88/// [`ConstDefault::DEFAULT`]: trait.ConstDefault.html#associatedconstant.DEFAULT
89#[cfg(feature = "const_default")]
90#[cfg_attr(feature = "docsrs", doc(cfg(feature = "const_default")))]
91#[macro_export]
92macro_rules! const_default {
93    () => {
94        $crate::ConstDefault::DEFAULT
95    };
96    ($This:ty) => {
97        <$This as $crate::ConstDefault>::DEFAULT
98    };
99}