Rust derive default on enum to remove need for impl block

367 Views Asked by At
 ~/Workspace/microscaler/docker-api-rs  on fix/linting-issues  cargo clippy --all-targets --all-features -- -D clippy::all -Z macro-backtrace                                                                ✔  at 20:14:11 
    Checking docker-api v0.12.2 (/Users/casibbald/Workspace/microscaler/docker-api-rs)
error: this `impl` can be derived
  --> src/opts/container.rs:50:1
   |
50 | / impl Default for Isolation {
51 | |     fn default() -> Self {
52 | |         Isolation::Default
53 | |     }
54 | | }
   | |_^
   |
   = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#derivable_impls
   = note: `-D clippy::derivable-impls` implied by `-D clippy::all`
   = help: remove the manual implementation...
help: ...and instead derive it...
   |
43 | #[derive(Default)]
   |
help: ...and mark the default variant
   |
45 ~     #[default]
46 ~     Default,
   |

error: could not compile `docker-api` due to previous error
warning: build failed, waiting for other jobs to finish...
error: could not compile `docker-api` due to previous error

The following help page is referred to: https://rust-lang.github.io/rust-clippy/master/index.html#derivable_impls

However, adding #[derive(Default)] does not seem so straightforward when multiple items exist.

Source code here: https://github.com/microscaler/docker-api-rs/blob/d85deec98a10dcc2f6a1ed7c324010e28d437941/src/opts/container.rs#L50

The following does not work:

    Checking docker-api v0.12.2 (/Users/casibbald/Workspace/microscaler/docker-api-rs)
error: no default declared
   --> src/opts/container.rs:41:10
    |
41  | #[derive(Default, Clone, Debug, Serialize, Deserialize)]
    |          ^^^^^^^ in this derive macro expansion
    |
   ::: /Users/casibbald/.rustup/toolchains/nightly-aarch64-apple-darwin/lib/rustlib/src/rust/library/core/src/default.rs:186:1
    |
186 | pub macro Default($item:item) {
    | ----------------- in this expansion of `#[derive(Default)]`
    |
    = help: make a unit variant default by placing `#[default]` above it
1

There are 1 best solutions below

3
Finomnis On

Read the compiler/linter messages, they tell you exactly what to do:

   = help: remove the manual implementation...
help: ...and instead derive it...
   |
43 | #[derive(Default)]
   |
help: ...and mark the default variant
   |
45 ~     #[default]
46 ~     Default,
   |
 = help: make a unit variant default by placing `#[default]` above it

Like this:

#[derive(Default, Clone, Debug)]
pub enum Isolation {
    #[default]
    Default,
    Process,
    HyperV,
}