'Golang - handle structs polymorphically [duplicate]

I wish to use multiple structs which inherits from the same Base struct in a polymorphic manner.

Given those structs:

type Base struct { X bool }

type A struct {
  Base // inherit Base
  A bool
}

type B struct {
  Base // inherit Base
  B bool
}

I would like to pass either of those structs as an argument to a function polymorphically, and maybe read (or update) one of the Base struct fields:

func CheckIfX(base *Base) bool { // supposed to be a polymorphic function..
  return base.X
}

b := &B{
  Base{
    X: true,
  },
  B: true,
}

CheckIfX(b) // fail with error..

What I have tried up until now:

  1. Using interface{} and dynamic parsing within the function (link to playground)
  2. Make structs inherit from an interface (link to playground). Drawbacks:
  • No actual need of implementing methods on my use case, so feels like an overkill
  • Structs wont parse as expected (for example when trying to save on Firestore..)

I would also like to ask:

Lets say we couldn't come up with something better than dynamic parsing, would you consider it a better practice than simply use 2 (or more) separet functions (rather than forcing it on a single one)?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source