I recently bought the MEAP for 100 Go Mistakes and How to Avoid Them by Teiva Harsanyi since it looked interesting and it is the kind of book I want to see more of.

Embedding in Go Link to heading

Embedding in Go is something that took a very long time for it to really click in my head. You just put a list a type without a name and magically things happen. Starting off this was really confusing since it isn’t clear where the embedded method being called is defined. I still think it is embedding isn’t ideal in most cases and try to avoid it, but it is a cool concept and is useful in some contexts.

Gotcha Link to heading

One of the examples Teiva covers regarding mistakes with using JSON is more widely concerned with embedding in general and the possiblity of unintended side effects.

type Data struct {
    Value int
    time.Time
}

data := Data{
    Value: 1234,
    Time: time.Now(),
}

b, _ := json.Marshal(data)

The value of string(b) is an RFC3339 formatted time, with no other field info. This happens because time.Time implements the json.Marshaler interface. But this isn’t the only interface that Marshal considers before doing its default behavior, encoding.TextMarshaler is also checked.

Solution Link to heading

There are obviously a lot of ways this kind of side effects could spring up and cause headaches so generally best to avoid using embedded types. Uber’s Go Style Guide even has a section about this very topic.