語言規範不允許使用它。從規範相關部分: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