语言规范不允许使用它。从规范相关部分:Struct types:
A field declared with a type but no explicit field name is an anonymous field, also called an embedded field or an embedding of the type in the struct. An embedded type must be specified as a type name T
or as a pointer to a non-interface type name *T
, and T
itself may not be a pointer type. The unqualified type name acts as the field name.
一个指针,一个接口类型是很少有用的,因为一个接口类型可以容纳一个指针或非指针值。
话虽如此,如果实现您的IFile
类型的具体类型为指针类型,然后指针值将被包裹在IFile
接口类型值,所以你还是要嵌入IFile
,只是价值实现IFile
将是一个指针值,例如
// Let's say *FileImpl implements IFile:
f := TestFile{IFile: &FileImpl{}}
编辑:回答您的评论:
首先,这是捷径,而不是C++。在Go中,接口不是指针,但它们表示为一对(type;value)
,其中“值”可以是指针或非指针。更多关于这个在博客文章:The Laws of Reflection: The representation of an interface。
其次,如果FileImpl
是一种类型,f := TestFile{IFile : &FileIml}
显然是一个编译时错误,你需要的*FileImpl
和&FileImpl
值显然不是。你需要例如composite literal这是&FileImpl{}
的形式,所以它应该是我上面发布的。
因为它被禁止。 – Volker