Say we have 2 structs sharing a property with the same name and purpose, but of different size:
type (
L16 struct {
Length uint16
}
L32 struct {
Length uint32
}
)
The goal is to make those structs have a GetLength
method with exactly the same signature and implementation:
func (h *L16) GetLength() int {
return int(h.Length)
}
func (h *L32) GetLength() int {
return int(h.Length)
}
— but to avoid repeating the implementation for each struct.
So I try:
type (
LengthHolder interface {
GetLength() int
}
LengthHolderStruct struct {
LengthHolder
}
L16 struct {
LengthHolderStruct
Length uint16
}
L32 struct {
LengthHolderStruct
Length uint32
}
)
func (h *LengthHolderStruct) GetLength() int {
return int(h.Length)
}
— but that errors with h.Length undefined (type *LengthHolderStruct has no field or method Length)
.
How do we do it?