Mention #[default]
in E0655 code index
This commit is contained in:
parent
9e136a30a9
commit
d520b18316
1 changed files with 16 additions and 4 deletions
|
@ -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
|
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.
|
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
|
For the case where the desired default variant has no data, you can annotate
|
||||||
hand":
|
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 {
|
enum Food {
|
||||||
Sweet,
|
Sweet(i32),
|
||||||
Salty,
|
Salty,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Default for Food {
|
impl Default for Food {
|
||||||
fn default() -> Food {
|
fn default() -> Food {
|
||||||
Food::Sweet
|
Food::Sweet(1)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue