简体   繁体   English

Go 错误:“嵌入式类型不能是指向接口的指针”

[英]Go error: "embedded type cannot be a pointer to interface"

The following code gives compile-time error:以下代码给出编译时错误:

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

type TestFile struct {
   *IFile
}

Error:错误:

./test.go:18: embedded type cannot be a pointer to interface ./test.go:18: 嵌入式类型不能是指向接口的指针

Why can't I embed *IFile ?为什么我不能嵌入*IFile

The language spec does not allow it.语言规范不允许这样做。 Relevant section from the spec: 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.嵌入类型必须指定为类型名称T指向非接口类型名称*T的指针,并且T本身可能不是指针类型。 The unqualified type name acts as the field name.非限定类型名称充当字段名称。

A pointer to an interface type is very rarely useful, as an interface type may hold a pointer or a non-pointer value.指向接口类型的指针很少有用,因为接口类型可能包含指针或非指针值。

Having said that, if a concrete type that implements your IFile type is a pointer type, then a pointer value will be wrapped in an interface value of type IFile , so you still have to embed IFile , just the value that implements IFile will be a pointer value, eg话虽如此,如果实现您的IFile类型的具体类型是指针类型,那么指针值将被包装在IFile类型的接口值中,因此您仍然必须嵌入IFile ,只是实现IFile的值将是指针值,例如

// Let's say *FileImpl implements IFile:
f := TestFile{IFile: &FileImpl{}}

Edit: Answer to your comment:编辑:回答您的评论:

First, this is Go, not C++.首先,这是 Go,而不是 C++。 In Go, interfaces are not pointers, but they are represented as a pair of (type;value) , where "value" may be pointer or non-pointer.在 Go 中,接口不是指针,而是表示为一对(type;value) ,其中“值”可以是指针或非指针。 More about this in blog post: The Laws of Reflection: The representation of an interface .博客文章中有关此的更多信息: 反射定律:接口的表示

Second, if FileImpl is a type, f := TestFile{IFile : &FileIml} is obviously a compile-time error, you need a value of *FileImpl and &FileImpl clearly isn't.其次,如果FileImpl是一个类型, f := TestFile{IFile : &FileIml}显然是一个编译时错误,你需要一个*FileImpl的值,而&FileImpl显然不是。 You need for example a composite literal which is in the form of &FileImpl{} , so it should be as I posted above.例如,您需要一个形式为&FileImpl{}复合文字,所以它应该是我在上面发布的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM