如果您在结构体中嵌入了一个接口,并且在使用该结构体时遇到问题,请确保将该接口作为指针类型嵌入。这样做可以避免出现意外的行为。
示例代码:
type Interface interface {
Method()
}
type Struct1 struct {
Interface
}
type Struct2 struct {
*Interface
}
func main() {
s1 := &Struct1{} // OK
s2 := &Struct2{} // OK
s3 := &Struct1{&InterfaceImpl{}} // NOT OK
s4 := &Struct2{&InterfaceImpl{}} // OK
}
在上面的示例中,Struct1中嵌入了Interface接口,而Struct2中嵌入了*Interface指针。因此,初始化Struct1时必须传递实现Interface接口的具体结构体,而在初始化Struct2时,可以传递InterfaceImpl结构体的指针或nil。
从实践角度看,这意味着无论何时将接口嵌入到结构体中,请使用指针类型,并在初始化结构体时避免传递实体实现。