Search code examples
goembedding

Is an embedded error exported?


According to the Go language spec, I can embed a type in a struct.

There is a weird case with the error interface. It is not uppercased, so I assume it is not exported as a type. But it is defined by the language. So if I have a struct like this:

package foo

type Err struct {
    error
}

is the embedded error exported? Does Err satisfy the error interface?

Can I access it from another package, i.e. is the following ok?

package main

import "errors"
import "fmt"
import "foo"

func main() {
    e := foo.Err{}
    e.error = errors.New("Hello world!") // is this okay?
    fmt.Println(e.Error())
}

Solution

  • When you embed an error interface into a struct, basically, you add a field named error with type error to it.

    Because it's embedded your struct now also implements all of it's methods. That means your struct satisfies the error interface and you can call Error() on it or just pass it to Println as it is and it will type assert it into error and call Error() for you https://play.golang.org/p/0VxUUX2l-z

    Obviously, because field is named error it's not exported. But the struct still satisfies the error interface because it has Error() method.

    Interesting consequence of this is that if you don't initialize the field Println will panic because it will try to call Error() on nil https://play.golang.org/p/XctFgKZI-K