Default in Rust

In Rust, the concept of "default" is a versatile feature that allows developers to define fallback values or behaviors for types, functions, and structures. This is particularly useful in scenarios where optional parameters or default values are needed, enhancing the flexibility and usability of Rust code. The Default trait and Rust macros are two primary mechanisms through which default values are implemented and utilized.

Overview of the Default Trait

The Default trait in Rust provides a standardized way to define default values for types. It acts like a no-argument new() method, allowing for the initialization of types with standard values. This trait is especially useful when working with struct parameters, as it can be derived for types where all fields also implement Default. This makes it easy to instantiate types with default values using methods like .unwrap_or_default().

Implementing the Default Trait

To implement the Default trait for a custom type, you define the default() method, which returns an instance of the type with the desired default values. Here is an example of implementing Default for a Character struct:

#[derive(Debug)]
struct Character {
    name: String,
    age: u8,
    height: u32,
    weight: u32,
    lifestate: LifeState,
}

#[derive(Debug)]
enum LifeState {
    Alive,
    Dead,
    NeverAlive,
    Uncertain,
}

impl Default for Character {
    fn default() -> Self {
        Self {
            name: "Billy".to_string(),
            age: 15,
            height: 170,
            weight: 70,
            lifestate: LifeState::Alive,
        }
    }
}

fn main() {
    let character_1 = Character::default();

    println!(
        "The character {:?} is {:?} years old.",
        character_1.name, character_1.age
    );
}

In this example, the Character struct is given default values such as the name "Billy", age 15, height 170, weight 70, and a life state of Alive.

Using Default with Structs

The Default trait can be automatically derived for structs where all fields implement Default. This is particularly useful for simple data structures. Consider the following Size struct:

#[derive(Debug, Default)]
struct Size {
    height: f64,
    length: f64,
    width: f64,
}

fn main() {
    let only_height = Size {
        height: 1.0,            // Makes height 1.0
        ..Default::default()    // For the rest, uses their default values
    };
    println!("{only_height:?}");
}

In this example, the Size struct has fields of type f64, which already implement Default. By deriving Default, you can easily create a Size instance with default values of 0.0 for each field, or override specific fields as needed.

Default Values in the Standard Library

Many types in the Rust standard library implement the Default trait. Common default values include 0 for numeric types, "" for strings, and false for booleans. These defaults are intuitive and prevent unexpected behavior. Here is a quick example demonstrating default values for some standard types:

fn main() {
    let default_i8: i8 = Default::default();
    let default_str: String = Default::default();
    let default_bool: bool = Default::default();

    println!("'{default_i8}', '{default_str}', '{default_bool}'");
}

This code will output '0', '', 'false', showcasing the default values for an i8, a String, and a bool.

Practical Use of Default with std::mem::take

The Default trait is also useful in conjunction with functions like take() from the std::mem module. This function requires the type to implement Default to replace the existing value with its default. Here is an example:

use std::mem;

#[derive(Debug)]
struct Bank {
    money_inside: u32,
    money_at_desk: DeskMoney,
}

#[derive(Debug)]
struct DeskMoney(u32);

impl Default for DeskMoney {
    fn default() -> Self {
        Self(50) // default is always 50, not 0.
    }
}

fn main() {
    let mut bank_of_klezkavania = Bank { // Sets up our bank
        money_inside: 5000,
        money_at_desk: DeskMoney(500),
    };

    let money_stolen = mem::take(&mut bank_of_klezkavania.money_at_desk);
    println!("Stole {} Klezkavanian credits", money_stolen.0);
    println!("{bank_of_klezkavania:?}");
}

In this example, the DeskMoney struct has a default value of 50. The mem::take function is used to replace the money_at_desk field with its default value, while returning the original value.

Default in Rust Macros

In Rust, macros can simulate default arguments, providing fallback values when none are specified. This is particularly useful for functions or structures that benefit from optional parameters with default values.

Simulating Default Arguments with Macros

Macros in Rust can create functions with optional parameters by simulating default arguments. This allows functions to be called with varying numbers of arguments, providing default values when certain arguments are omitted. The following example demonstrates how a macro can provide default greetings:

macro_rules! greeting {
    ($name:literal) => {
        base_greeting_fn($name,"Hello")
    };
    ($name:literal,$greeting:literal) => {
        base_greeting_fn($name,$greeting)
    }
}

In this example, the greeting! macro allows for a default greeting of "Hello" if no specific greeting is provided.

Handling Default Implementations in Structs

When dealing with structs, the Default trait can provide default values for struct fields. However, some fields may not implement Default. A macro can handle such scenarios:

use builder_macro::Builder;

struct DoesNotImplementDefault;      #1

#[derive(Builder)]
#[builder_defaults]
struct ExampleStruct {
    not: DoesNotImplementDefault     #2
}

fn main() {}
#1 This struct does not implement Default.
#2 But we use it in a struct that uses the default fallback.

In this example, DoesNotImplementDefault does not implement Default, but is used within ExampleStruct, which uses default fallbacks for other fields. This is useful when certain fields are expected to be provided explicitly, while others can rely on default values.

For more detailed information, you can refer to the Learn Rust in a Month of Lunches and Write Powerful Rust Macros books.

| Book Title | Usage of default | Technical Depth | Connections to Other Concepts | Examples Used | Practical Application |
|------------|------------------|-----------------|-------------------------------|---------------|-----------------------|
| [Learn Rust in a Month of Lunches](https://www.manning.com/books/learn-rust-in-a-month-of-lunches) | Discusses the `Default` trait as a way to define default values for types, useful in scenarios like `.unwrap_or_default()`. [more](https://livebook.manning.com/book/learn-rust-in-a-month-of-lunches/chapter-21/7) | Explains the implementation of the `Default` trait and its automatic derivation for structs. [more](https://livebook.manning.com/book/learn-rust-in-a-month-of-lunches/chapter-15/1) | Connects `Default` with `std::mem::take` and other standard library types. [more](https://livebook.manning.com/book/learn-rust-in-a-month-of-lunches/chapter-15/1) | Provides examples with structs like `Character` and `Size`, and standard types like `i8`, `String`, and `bool`. [more](https://livebook.manning.com/book/learn-rust-in-a-month-of-lunches/chapter-15/1) | Shows practical use with `std::mem::take` to replace values with defaults. [more](https://livebook.manning.com/book/learn-rust-in-a-month-of-lunches/chapter-21/7) |
| [Write Powerful Rust Macros](https://www.manning.com/books/write-powerful-rust-macros) | Uses macros to simulate default arguments, providing flexibility in function calls. [more](https://livebook.manning.com/book/write-powerful-rust-macros/chapter-2/65) | Discusses handling default implementations in structs, especially when fields do not implement `Default`. [more](https://livebook.manning.com/book/write-powerful-rust-macros/chapter-8/86) | Explores the use of macros to handle default values in functions and structs. [more](https://livebook.manning.com/book/write-powerful-rust-macros/chapter-2/81) | Includes examples like the `greeting!` macro and handling structs with non-default fields. [more](https://livebook.manning.com/book/write-powerful-rust-macros/chapter-8/86) | Demonstrates the use of macros to enhance function and struct usability with default values. [more](https://livebook.manning.com/book/write-powerful-rust-macros/chapter-2/65) |

FAQ (Frequently asked questions)

What does the Default implementation for DeskMoney return?