2016-11-09 50 views
0

下面的代碼提供編譯時錯誤:轉到錯誤:「嵌入式不能是指針接口」

type IFile interface { 
    Read() (n int, err error) 
    Write() (n int, err error) 
} 

type TestFile struct { 
    *IFile 
} 

錯誤:

./test.go:18: embedded type cannot be a pointer to interface

爲什麼我不能嵌入*IFile

+0

因爲它被禁止。 – Volker

回答

1

語言規範不允許使用它。從規範相關部分: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{}的形式,所以它應該是我上面發佈的。

+0

類型的IFile接口{ 讀()(N INT,ERR出錯) 寫()(N INT,ERR出錯) } 類型FileImp { 串FILE_NAME ..... } 類型TESTFILE結構{ 的IFile } F:= {TESTFILE的IFile:FileIml} 是否F包含FileImp場的內存拷貝? –

+0

@sotter'f.IFile'字段是一個接口類型,它包含'FileImpl'的副本,所以是的,'f'包含'FileImpl'的副本。如果你不想那麼做,可以使用poitner,例如'&FileImpl',所以只會存儲指針的一個副本,但它將指向相同的'FileImpl'值。 – icza

+0

謝謝,但我明白,'f:= TestFile {IFile:&FileIml}'不能構建。在C++中,Interface是一個指針,這就是爲什麼我要在golang中輸入TestFile struct {* IFile}的原因。 –