Autodefault automatically makes your struct literals fill themselves with `..default()`

Overview

Crates.io Crates.io docs.rs

autodefault

A library that automatically inserts ..Default::default() for you.

The pitch

Has this ever happened to you?

#[derive(Debug, Default, PartialEq, Eq)]
struct Inner {
    x: i32,
    y: i32,
    z: i32,
}

#[derive(Debug, Default, PartialEq, Eq)]
struct Mid {
    a: Inner,
    b: Inner,
    c: Inner,
    d: Inner
}

#[derive(Debug, Default, PartialEq, Eq)]
struct Outer {
    mid1: Mid,
    mid2: Mid,
    mid3: Mid,
    mid4: Mid,
}

fn build_outer() -> Outer {
    Outer {
        mid1: Mid {
            a: Inner {
                x: 10,
                ..Default::default()  // :D
            },
            b: Inner {
                y: 10,
                ..Default::default()  // :)
            },
            ..Default::default()  // :|
        },
        mid2: Mid {
            b: Inner {
                z: 10,
                ..Default::default()  // :/
            },
            ..Default::default()  // :(
        },
        ..Default::default()  // >:(
    }
}

Wouldn't it be nice if you could omit all the tedious ..Default::default() calls when building deeply nested struct literals? Now you can! With autodefault, it's never been easier to build up a large struct literal for your tests, bevy components, or anything else you might need!. Simply tag any function with the #[autodefault] attribute and let us handle the rest:

use autodefault::autodefault;

#[autodefault]
fn build_outer_simple() -> Outer {
    Outer {
        mid1: Mid {
            a: Inner { x: 10 },
            b: Inner { y: 10 },
        },
        mid2: Mid {
            b: Inner { z: 10 },
        }
    }
}  // :O

assert_eq!(build_outer(), build_outer_simple())

It's never been easier! Check out the reference documentation for more details.

You might also like...
A tool that switch default audio playback device on windows.

AudioSwitch A tool built by Rust that can switch default audio playback device on windows. How to use specify which device you want to use Execute it

Shellfirm - Intercept any risky patterns (default or defined by you) and prompt you a small challenge for double verification
Shellfirm - Intercept any risky patterns (default or defined by you) and prompt you a small challenge for double verification

shellfirm Opppppsss you did it again? 😱 😱 😰 Protect yourself from yourself! rm -rf * git reset --hard before saving? kubectl delete ns which going

Default implementation of the Wayland protocol for use with wl

Wayland An implementation of core Wayland interfaces and convenience functions for accelerating the development of Wayland clients and servers using t

⚡ A blazing fast alternative to the default Windows delete.
⚡ A blazing fast alternative to the default Windows delete.

Turbo Delete A blazing fast alternative to the default Windows delete. Turbodelete is a blazing fast alternative to the default Windows delete functio

Yet Another Kalman Filter Implementation. As well as Lie Theory (Lie group and algebra) on SE(3). [no_std] is supported by default.

yakf - Yet Another Kalman Filter Yet Another Kalman Filter Implementation, as well as, Lie Theory (Lie group, algebra, vector) on SO(3), SE(3), SO(2),

A library that makes it VERY easy to run Holochain as a library, from your own binary, with great defaults

embedded-holochain-runner A library that makes it VERY easy to run Holochain as a library, from your own binary, with great defaults How it will work

Warp is a blazingly fast, Rust-based terminal that makes you and your team more productive at running, debugging, and deploying code and infrastructure.
Warp is a blazingly fast, Rust-based terminal that makes you and your team more productive at running, debugging, and deploying code and infrastructure.

Warp is a blazingly fast, Rust-based terminal that makes you and your team more productive at running, debugging, and deploying code and infrastructure.

Easy pretty print your Rust struct into single element or table

Easy pretty print your Rust struct into single element or table

A PackageJson struct for your rust code.

📦️ package_json_schema Load a package.json file as a PackageJson struct. Why? You want to load a package.json file and interact with it as a struct.

A simple self-contained CLI tool that makes it easy to efficiently encrypt/decrypt your files.

cryptic A simple self-contained CLI tool that makes it easy to efficiently encrypt/decrypt your files. Contents Features Building Usage License Featur

A procedural macro to generate a new function implementation for your struct.

Impl New 🦀 A procedural macro to generate a new function implementation for your struct. 🚀 Add to your project Add this to your Cargo.toml: [depende

deductive verification of Rust code. (semi) automatically prove your code satisfies your specifications!
deductive verification of Rust code. (semi) automatically prove your code satisfies your specifications!

Le marteau-pilon, forges et aciéries de Saint-Chamond, Joseph-Fortuné LAYRAUD, 1889 About Creusot is a tool for deductive verification of Rust code. I

Parse command line arguments by defining a struct.

StructOpt Parse command line arguments by defining a struct. It combines clap with custom derive. Documentation Find it on Docs.rs. You can also check

proc-macro for accessing struct field names at runtime

field_names field_names is a Rust crate to expose a field or variant names from source code as strings at runtime. Example Consider a simple struct su

Serialize/DeSerialize for Rust built-in types and user defined types (complex struct types)

Serialize/DeSerialize for Rust built-in types and user defined types (complex struct types)

A Rust CLI that makes mechanical keyboard sound effects on every key press
A Rust CLI that makes mechanical keyboard sound effects on every key press

Rustyvibes A Rust CLI that makes mechanical keyboard sound effects on every key press Rustyvibes.mp4 Installation macOS: brew install kb24x7/rustyvibe

A rust library that makes reading and writing memory of the Dolphin emulator easier.

dolphin-memory-rs A crate for reading from and writing to the emulated memory of Dolphin in rust. A lot of internals here are directly based on aldela

A proc-macro to get Vecu8 from struct and vise versa

byteme A proc-macro to convert a struct into Vec and back by implemeting From trait on the struct. The conversion is Big Endian by default. We have ma

Struct mocking library for Rust

faux   A library to create mocks out of structs. faux allows you to mock the methods of structs for testing without complicating or polluting your cod

Comments
  • What else can it do?

    What else can it do?

    Would be cool if we could have something like:

    aws: Default::default(),
    battery: Default::default()
    

    which autodefault could solve I suppose. Maybe making it so you could do:

    aws,
    battery
    

    etc.

    opened by Milo123459 13
  • Do not propagate onto function's inner items

    Do not propagate onto function's inner items

    If you would like to use this crate's functionality inside of inner function definitions, then you should use #[autodefault] at each step:

    #[autodefault]
    fn demo() {
        let x = Foo {a: 10, b: 10};
    
        #[autodefault]
        fn inner() {
            let x = Foo {a: 10, b: 10};
        }
    }
    
    opened by ZetaNumbers 1
  • Does not work on struct literals in `vec!` macro

    Does not work on struct literals in `vec!` macro

    #[derive(Default)]
    struct Foo {
        x: i32,
        y: i32,
        z: i32,
    }
    
    #[autodefault::autodefault]
    fn foos() -> Vec<Foo> {
        let f1 = Foo { x: 1 };
    
        vec![Foo { y: 1 }, Foo { z: 1 }]
    }
    

    using cargo expand gives

    pub mod ex_demo {
        struct Foo {
            x: i32,
            y: i32,
            z: i32,
        }
        #[automatically_derived]
        #[allow(unused_qualifications)]
        impl ::core::default::Default for Foo {
            #[inline]
            fn default() -> Foo {
                Foo {
                    x: ::core::default::Default::default(),
                    y: ::core::default::Default::default(),
                    z: ::core::default::Default::default(),
                }
            }
        }
        fn foos() -> Vec<Foo> {
            let f1 = Foo {
                x: 1,
                ..::core::default::Default::default()
            };
            <[_]>::into_vec(box [Foo { y: 1 }, Foo { z: 1 }])
        }
    }
    

    Which gives errors

    error[E0063]: missing fields `x` and `z` in initializer of `Foo`
      --> src\ex_demo.rs:12:10
       |
    12 |     vec![Foo { y: 1 }, Foo { z: 1 }]
       |          ^^^ missing `x` and `z`
    
    error[E0063]: missing fields `x` and `y` in initializer of `Foo`
      --> src\ex_demo.rs:12:24
       |
    12 |     vec![Foo { y: 1 }, Foo { z: 1 }]
       |                        ^^^ missing `x` and `y`
    
    opened by aDotInTheVoid 2
Owner
Nathan West
I make the sound that nerds make He/Him/His
Nathan West
This crate allows writing a struct in Rust and have it derive a struct of arrays layed out in memory according to the arrow format.

Arrow2-derive - derive for Arrow2 This crate allows writing a struct in Rust and have it derive a struct of arrays layed out in memory according to th

Jorge Leitao 29 Dec 27, 2022
🛡️ Automatically protect the default branch of new repositories in a GitHub organization

The Branch Autoprotector watches a GitHub organization and automatically protects the default branch in new repositories. This service notifies the creator of the default branch of this automatic branch protection setup by filing an issue in the repository.

Branch Autoprotector 2 Jan 31, 2022
Rust crate: Overloaded Literals to construct your datatypes without boilerplate and with compile-time validation.

overloaded_literals   Overloaded Literals to construct your datatypes without boilerplate and with compile-time validation. Features Compile-time vali

Qqwy / Marten 6 Apr 14, 2023
Fill Apache Arrow record batches from an ODBC data source in Rust.

arrow-odbc Fill Apache Arrow arrays from ODBC data sources. This crate is build on top of the arrow and odbc-api crate and enables you to read the dat

Markus Klein 21 Dec 27, 2022
Sample Artemis bot to fill UniswapX orders using on-chain liquidity

UniswapX Atomic Filler This is a sample Artemis bot that fills UniswapX orders atomically using Uniswap v2 and v3 liquidity. Feel free to fork and mod

null 102 Jul 25, 2023
Parsing and inspecting Rust literals (particularly useful for proc macros)

litrs: parsing and inspecting Rust literals litrs offers functionality to parse Rust literals, i.e. tokens in the Rust programming language that repre

Lukas Kalbertodt 31 Dec 26, 2022
Rust crate for obfuscating string literals.

Obfustring This crate provides a obfuscation macro for string literals. This makes it easy to protect them from common reverse engineering attacks lik

null 7 Mar 1, 2023
Rust-based replacement for the default Minecraft renderer

wgpu-mc ?? A blazing fast alternative renderer for Minecraft Intro WebGPU is a new web specification designed to provide modern graphics and compute c

Birb 1 Jun 28, 2022
zero runtime cost default arguments in rust

Default Arguments in Rust Enables default arguments in rust by macro in zero cost. Just wrap function with default_args! and macro with name of functi

Jaeyong Sung 73 Sep 6, 2022
GitHub CLI extension to show & rename the default branch.

gh-default-branch GitHub CLI extension to show & rename the default branch. rename subcommand was inspired by this gist. ⚠️ Caution The rename subcomm

Daido Shota 8 Sep 22, 2022