patterns/idioms/default.md

59 lines
1.9 KiB
Markdown
Raw Normal View History

2016-12-31 13:56:54 +00:00
# The `Default` Trait
## Description
2017-02-15 08:16:26 +00:00
Many types in Rust have a [constructor]. However, this is *specific* to the
2016-12-31 13:56:54 +00:00
type; Rust cannot abstract over "everything that has a `new()` method". To
allow this, the [`Default`] trait was conceived, which can be used with
containers and other generic types (e.g. see [`Option::unwrap_or_default()`]).
Notably, some containers already implement it where applicable.
Not only do one-element containers like `Cow`, `Box` or `Arc` implement
`Default` for contained `Default` types, one can automatically
`#[derive(Default)]` for structs whose fields all implement it, so the more
types implement `Default`, the more useful it becomes.
On the other hand, constructors can take multiple arguments, while the
`default()` method does not. There can even be multiple constructors with
different names, but there can only be one `Default` implementation per type.
2016-12-31 13:56:54 +00:00
## Example
```rust
// note that we can simply auto-derive Default here.
#[derive(Default)]
2017-02-09 08:10:55 +00:00
struct MyConfiguration {
// Option defaults to None
output: Option<Path>,
// Vecs default to empty vector
search_path: Vec<Path>,
// Duration defaults to zero time
timeout: Duration,
// bool defaults to false
check: bool,
2016-12-31 13:56:54 +00:00
}
2017-02-09 08:10:55 +00:00
impl MyConfiguration {
// add setters here
2016-12-31 13:56:54 +00:00
}
2020-03-05 10:28:58 +00:00
fn main() {
// construct a new instance with default values
let mut conf = MyConfiguration::default();
// do somthing with conf here
}
2016-12-31 13:56:54 +00:00
```
## See also
2017-02-15 08:16:26 +00:00
- The [constructor] idiom is another way to generate instances that may or may
2016-12-31 13:56:54 +00:00
not be "default"
- The [`Default`] documentation (scroll down for the list of implementors)
- [`Option::unwrap_or_default()`]
2017-02-16 07:50:43 +00:00
- [`derive(new)`]
2016-12-31 13:56:54 +00:00
2017-02-15 08:16:26 +00:00
[constructor]: ctor.md
2017-02-17 04:03:05 +00:00
[`Default`]: https://doc.rust-lang.org/stable/std/default/trait.Default.html
[`Option::unwrap_or_default()`]: https://doc.rust-lang.org/stable/std/option/enum.Option.html#method.unwrap_or_default
2017-02-16 07:50:43 +00:00
[`derive(new)`]: https://crates.io/crates/derive-new/