#default #traits #customization #macro #cute

macro cute_custom_default

Derive macro for Default trait with customization

3 stable releases

2.2.0 Aug 10, 2024
2.1.0 Mar 21, 2020
2.0.0 Apr 6, 2019
1.0.0 Apr 6, 2019

#2138 in Procedural macros

Download history 33/week @ 2024-08-16 24/week @ 2024-08-23 29/week @ 2024-08-30 31/week @ 2024-09-06 54/week @ 2024-09-13 51/week @ 2024-09-20 59/week @ 2024-09-27 27/week @ 2024-10-04 31/week @ 2024-10-11 29/week @ 2024-10-18 28/week @ 2024-10-25 66/week @ 2024-11-01 19/week @ 2024-11-08 11/week @ 2024-11-15 40/week @ 2024-11-22 26/week @ 2024-11-29

101 downloads per month

Apache-2.0

17KB
204 lines

CustomDefault

Build Crates.io Documentation

Derive macro for Default trait with customization


lib.rs:

CustomDefault

Provides derive macro for Default trait with customization point

Attributes

  • def_val=<value> - Specifies default value for field. Panics on incorrect type of field.
  • def_exp="expression" - Specifies expression to be placed as initializer to field. No pre-processing.

Usage

use cute_custom_default::CustomDefault;

pub fn default_value_string() -> &'static str {
    "default_value_string"
}

#[derive(CustomDefault)]
pub struct MyStruct {
    #[def_val='c']
    pub custom_char: char,
    #[def_val=b"my_bytes"]
    pub custom_bytes: [u8; 8],
    #[def_val=b"my_bytes"]
    pub custom_bytes_slice: &'static [u8],
    #[def_val=b'b']
    pub custom_default: u8,
    #[def_val=true]
    pub custom_bool: bool,
    pub normal_bool: bool,
    #[def_exp="\"Just my string\".to_owned()"]
    pub expression: String,
    #[def_exp="default_value_string()"]
    pub static_str: &'static str,
    #[def_val="Just my string"]
    pub string: String,
    #[def_val="Just my string"]
    pub static_str_again: &'static str,
    #[def_val=666]
    pub u32_field: u32,
    #[def_exp="std::u16::MAX"]
    pub u16_field: u16,
    #[def_exp="-655_555"]
    pub i32_field: i32,
}

fn main() {
    let my_struct = MyStruct::default();
    assert_eq!(my_struct.custom_char, 'c');
    assert_eq!(my_struct.custom_default, b'b');
    assert_eq!(&my_struct.custom_bytes, b"my_bytes");
    assert_eq!(my_struct.custom_bytes_slice, b"my_bytes");
    assert_eq!(my_struct.custom_bool, true);
    assert_eq!(my_struct.normal_bool, false);
    assert_eq!(my_struct.expression, "Just my string");
    assert_eq!(my_struct.static_str, default_value_string());
    assert_eq!(my_struct.string, "Just my string");
    assert_eq!(my_struct.static_str_again, "Just my string");
    assert_eq!(my_struct.u32_field, 666);
    assert_eq!(my_struct.u16_field, std::u16::MAX);
    assert_eq!(my_struct.i32_field, -655_555);
}

Dependencies

~215–650KB
~15K SLoC