假设我们有 2 个结构共享一个名称和用途相同但大小不同的属性:
type (
L16 struct {
Length uint16
}
L32 struct {
Length uint32
}
)
目标是使这些结构具有GetLength
具有完全相同签名和实现的方法:
func (h *L16) GetLength() int {
return int(h.Length)
}
func (h *L32) GetLength() int {
return int(h.Length)
}
——但要避免对每个结构重复实现。
所以我尝试:
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)
}
- 但错误与h.Length undefined (type *LengthHolderStruct has no field or method Length)
.
我们该怎么做呢?