Atonal
Atonal

Reputation: 530

Is there any point in embedding `json.Unmarshaller` or `encoding.BinaryUnmarshaller` into an interface X, besides ensuring X implements them?

I have interface like below:

type Car interface {
    json.Marshaler
    json.Unmarshaler
}

and a struct that implements above interface:

var _ Car = (*Honda)(nil)

The benefit of embedding a json marshaler into the interface is that I can call MarshalJSON method directly on a variable of the type Car.

I don't understand what would be the point of embedding an unmarshaler, though, because at compile time the compiler doesn't know the concrete type implementing the interface.

So, is there any point in embedding a json.Unmarshaller into Car, besides making sure Honda implements them?

Upvotes: 1

Views: 35

Answers (1)

Burak Serdar
Burak Serdar

Reputation: 51567

Interface embedding is simply interface composition. The resulting interface will have all the methods of the embedded interfaces. Writing:

type Car interface {
    json.Marshaler
    json.Unmarshaler
}

is equivalent to writing:

type Car interface {
    UnmarshalJSON([]byte,any) error
    MarshalJSON(any) ([]byte,error)
}

One benefit of such embedding is that whoever reads the Car interface can see that it has to support json marshal/unmarshaling using the stdlib conventions, which can be difficult to spot if the interface get large.

Upvotes: 2

Related Questions