Go中的嵌套接口
我在Go中有一个接口类型,它定义了一些方法,它们有自己的嵌套接口。大概是这样的:Go中的嵌套接口,go,interface,Go,Interface,我在Go中有一个接口类型,它定义了一些方法,它们有自己的嵌套接口。大概是这样的: type Store interface { Pack(key string) interface { Put(r io.Reader) (int, error) io.Closer } // ... other stuff ... } type Packer interface { Put(r io.Reader) (int, error)
type Store interface {
Pack(key string) interface {
Put(r io.Reader) (int, error)
io.Closer
}
// ... other stuff ...
}
type Packer interface {
Put(r io.Reader) (int, error)
io.Closer
}
现在,我定义了另一个接口,我们称之为Packer,它匹配Pack方法返回的内容,如下所示:
type Store interface {
Pack(key string) interface {
Put(r io.Reader) (int, error)
io.Closer
}
// ... other stuff ...
}
type Packer interface {
Put(r io.Reader) (int, error)
io.Closer
}
然后我可以实现两种类型的存储。一个具有返回打包器的Pack方法,另一个具有返回显式接口类型的Pack:
func (s *storeTypeA) Pack(key string) Packer { ... }
func (s *storeTypeB) Pack(key string) interface {
Put(r io.Reader) (int, error)
io.Closer
} { ... }
现在只有一个问题storeTypeA
实际上不再符合Store界面。如果我试图将其冒充为商店,则会出现以下错误:
prog.go: cannot use storeTypeA literal (type *storeTypeA) as type Store in assignment:
*storeTypeA does not implement Store (wrong type for Pack method)
have Pack(string) Packer
want Pack(string) interface { Close() error; Put(io.Reader) (int, error) }
但我不明白的是,Packer接口完全等于接口{Close()error;Put(io.Reader)(int,error)}
。那么为什么会出现错误呢
有没有办法解决这个问题
我想最明显的就是没有嵌套的接口,但我有点好奇为什么这会成为一个问题。我这样做是因为我希望能够在包之外定义接口,在包中我提供存储本身。
Packer
和interface{Close()error;Put(io.Reader)(int,error)}
是两种不同的类型。为什么在存储定义中需要匿名接口?@JimB:type Packer interface{Close()error;Put(io.Reader)(int,error)}
在我看来与interface{Close()error;Put(io.Reader)(int,error)}
相同?一个是“匿名”的,另一个有名字。类型a int
和类型B int
看起来也一样,但就Go的类型系统而言,它们是不同的类型。如何编写Go有很多问题。首先,为什么要使用嵌套接口?其次,为什么不导入提供Packer
接口的包,并将Packer
接口嵌入Store
接口?第三,为什么匿名接口要取代Packer
接口?