2016-11-09 27 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}的原因。 –