It's getting dark around Rusts' defaulting

Every programming language I know has an easy defaulting / initializing without or with extreme little boiler code, except Rust, until now.


“Normal” programming languages

In a lot of programming languages you can set a default or initializing value to a variable at the time of declaration, like this in ABAP: DATA: lv_int TYPE i VALUE 1. Or like in dart: int lv_int = 1; This is a convenient way of setting the first value to variable. One line with little boiler code (ABAP) or even none (dart). This is the way I want to declare variables.

The Rust way

This is a short description of how initialization in Rust works. The documentation is the best place to read about it in detail. In Rust you can't use such a short syntax to default or initialize variables. Here you have to pass the default values during instantiation which may lead to a lot of functions, because you have to pass the values to each property in the signature or use a whole function to default your values (example from rustfaq):

use std::default::Default;

struct User {
    username: String,
    active: bool,
    role: String,
}

impl Default for User {
    fn default() -> Self {
        User {
            // "guest" is a safe placeholder that won't break auth checks.
            username: String::from("guest"),
            // New users start active by policy.
            active: true,
            // Default role is restricted.
            role: String::from("viewer"),
        }
    }
}

This is a lot of unnecessary coding if you just want to default the values and have a structure with lot of properties. But this is the way, how rust works, until now

The dark Rust

In the nightly toolchain Rust added a new way of initializing structures: “The normal way”. In the current nightly, you are able to have the possibility to default your structures values like in other languages, by setting the value at declaration time. The features is called default _field_values and works like this: Add this feature to your Rust file: #![feature(default_field_values)] And let your struct derive the default: #[derive(Default)] And default your properties:

struct User {
    username: String::from("guest");
    active: bool = true,
    role: String::from("viewer"),
}

And that's it. It is as easy as in other languages and you keep your code cleaner as you do not need any boiler code anymore.

But wait

If you want to use this convenient feature, you have to keep in mind, that this is the nightly toolchain. Any new feature in the nightly can be removed again. So if you plan to use this, be prepared to change it back to the old way again. I don't think, that it is likely to be removed, as this is a cool quality of life feature which raises declaration to the standard level of programming languages. But I am not part of the Rust developers and can't tell whether this will become stable or not. So be warned to use this