3 ms·
`Default` is a trait[1] that can be implemented on any type that can be conceived to have a default value. For example, Option has something like: impl<T>
by estebank 5y ago
`Default` is a trait[1] that can be implemented on any type that can be conceived to have a default value. For example, Option has something like:
impl<T> Default for Option<T> {
fn default() -> Option<T> {
None
}
}
If every field of a struct impl Default, then you can you can use the `#[derive(Default)]` annotation to auto-fill that impl for that struct, otherwise you have to write it by hand.
The .. is the spread operator, and it takes every field of the value on the right and applies it to every field of the struct constructor on the left. This only works for the same type (it's not only looking at the field names).
`Default::default()` is a qualified call on the trait equivalent to `<_ as Default>::default()`, where `_` is inferred from context to be `BufferInfo`.
What that code is doing is saying "build a default BufferInfo with field buffer_usage set to VERTEX".
The spread operator has a limitation you might have intuited from the description that it can't work for types where some field(s) should always be set but not others. To get around that you can use the builder pattern
BufferInfo::with_buffer_usage(BufferUsage::VERTEX).build()
and there's a pre-RFC in flight to become an RFC to add support for
struct Foo {
field: i32 = 42,
}
let foo = Foo { .. };
[1]: https://doc.rust-lang.org/std/default/trait.Default.html https://doc.rust-lang.org/std/default/trait.Default.html