Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Confused about composition vs. inheritance

I’m trying to find the best way to tackle which I would normally solve with inheritance in a another language, but struggling to find the go way to do it.

I have a number of structs, that all share a common embedded struct. I want to use a common ‘method’ with these structs, and allow them to update a member of the embedded struct.

type EventMetaData struct {
    SystemId  string `json:"system_id"`
    Timestamp string `json:"timestamp"`
}

func (evd *EventMetaData) SetSystemId(systemId string) {
    evd.SystemId = systemId
}

type LoginEvent struct {
    *EventMetaData
    UserId    string `json:"user_id"`
    Method    string `json:"method"`
    Timestamp string `json:"timestamp"`
}

type LogoutEvent struct {
    *EventMetaData
    UserId string `json:"user_id"`
}

type CanSetEventMetaData interface {
    SetSystemId(string)
}

func FromPayload(ev *CanSetEventMetaData, payload []byte) (*E, error) {
    err := json.Unmarshal(payload, ev)
    if err != nil {
        return nil, err
    }
    ev.SetSystemId(config.systemId)
    return ev, nil
}

However, the line ev.SetSystemId returns an unresolved reference.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

In other languages I’ve used, I’d inherit the base class with the the SetSystemId method. I understand this is not the go way.

>Solution :

What you are doing is correct, however, the parameter ev is a pointer to an interface, it is not an interface. To fix:

func FromPayload(ev CanSetEventMetaData, payload []byte) (*E, error) {
...
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading