Reputation: 530
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
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