bevy/crates/bevy_utils/src/default.rs
Carter Anderson b6a647cc01 default() shorthand (#4071)
Adds a `default()` shorthand for `Default::default()` ... because life is too short to constantly type `Default::default()`.

```rust
use bevy::prelude::*;

#[derive(Default)]
struct Foo {
  bar: usize,
  baz: usize,
}

// Normally you would do this:
let foo = Foo {
  bar: 10,
  ..Default::default()
};

// But now you can do this:
let foo = Foo {
  bar: 10,
  ..default()
};
```

The examples have been adapted to use `..default()`. I've left internal crates as-is for now because they don't pull in the bevy prelude, and the ergonomics of each case should be considered individually.
2022-03-01 20:52:09 +00:00

30 lines
930 B
Rust

/// An ergonomic abbreviation for [`Default::default()`] to make initializing structs easier.
/// This is especially helpful when combined with ["struct update syntax"](https://doc.rust-lang.org/book/ch05-01-defining-structs.html#creating-instances-from-other-instances-with-struct-update-syntax).
/// ```
/// use bevy_utils::default;
///
/// #[derive(Default)]
/// struct Foo {
/// a: usize,
/// b: usize,
/// c: usize,
/// }
///
/// // Normally you would initialize a struct with defaults using "struct update syntax"
/// // combined with `Default::default()`. This example sets `Foo::bar` to 10 and the remaining
/// // values to their defaults.
/// let foo = Foo {
/// a: 10,
/// ..Default::default()
/// };
///
/// // But now you can do this, which is equivalent:
/// let foo = Foo {
/// a: 10,
/// ..default()
/// };
/// ```
#[inline]
pub fn default<T: Default>() -> T {
std::default::Default::default()
}