douche3791 2016-11-09 08:47
浏览 151
已采纳

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

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

Why can't I embed *IFile?

  • 写回答

1条回答 默认 最新

  • dsmgcse8876 2016-11-09 08:55
    关注

    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. 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, e.g.

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

    Edit: Answer to your comment:

    First, this is Go, not 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. 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. You need for example a composite literal which is in the form of &FileImpl{}, so it should be as I posted above.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮