What mechanism allows this to work?


I'm trying to wrap my head around this code. I don't understand what's the mechanism that allows you to pass an enum variant to map_err and have the compiler accept the code.

Any kind soul willing to ELI5? :smiley:

Looking at the docs, map_err takes an FnOnce. Is this trait automatically implemented for enums?

The compiler implicitly creates function objects with the same names as enum variants, you can read more about it here:



Here is an example of an explicit function declaration that works mostly like the implicit one:

pub struct BusError;

/// What you're asking about
pub enum Implicit {

/// What it's like
pub enum Explicit {
    Bus { e: BusError },
impl Explicit {
    pub fn Bus(e: BusError) -> Self {
        Self::Bus { e }

There are two differences between these:

  1. You can use Implicit::Bus() in pattern matching too; you can't do that with a user-defined function.
  2. The field name of the BusError field in Implicit::Bus is actually 0, not e. Only tuple-style structs and enum variants can have these numbered names; they can't be declared explicitly.
1 Like

Thank you for the explanations!