Mention #[default] in E0655 code index

This commit is contained in:
Esteban Küber 2024-12-13 22:59:26 +00:00
parent 9e136a30a9
commit d520b18316

View file

@ -16,18 +16,30 @@ The `Default` cannot be derived on an enum for the simple reason that the
compiler doesn't know which value to pick by default whereas it can for a
struct as long as all its fields implement the `Default` trait as well.
If you still want to implement `Default` on your enum, you'll have to do it "by
hand":
For the case where the desired default variant has no data, you can annotate
it with `#[default]` to derive it:
```
#[derive(Default)]
enum Food {
#[default]
Sweet,
Salty,
}
```
In the case where the default variant does have data, you will have to
implement `Default` on your enum "by hand":
```
enum Food {
Sweet,
Sweet(i32),
Salty,
}
impl Default for Food {
fn default() -> Food {
Food::Sweet
Food::Sweet(1)
}
}
```