我想创建一个界面,以便轻松添加新的存储后端。golang API接口,我错过了什么?
package main
// Storage is an interface to describe storage backends
type Storage interface {
New() (newStorage Storage)
}
// File is a type of storage that satisfies the interface Storage
type File struct {
}
// New returns a new File
func (File) New() (newFile Storage) {
newFile = File{}
return newFile
}
// S3 is a type of storage that satisfies the interface Storage
type S3 struct {
}
// New returns a new S3
func (S3) New() (newS3 S3) {
newS3 = S3{}
return newS3
}
func main() {
// List of backends to choose from
var myStorage map[string]Storage
myStorage["file"] = File{}
myStorage["s3"] = S3{}
// Using one of the backends on demand
myStorage["file"].New()
myStorage["s3"].New()
}
但似乎无法定义,满足应该返回满足接口本身以及对象的功能。
File.New()返回满足存储的Storage类型的对象。
S3.New()返回S3类型的对象。 S3应该满足接口存储很好,但我得到这个:
./main.go:32: cannot use S3 literal (type S3) as type Storage in assignment:
S3 does not implement Storage (wrong type for New method)
have New() S3
want New() Storage
我在做什么错? 我希望我缺少一些基本的东西。
S3的结构和文件结构有diferent返回obj类型,尽量让他们都通过使用接口作为回报返还相同种类的obj。并且在将struct作为接口返回时不要忘记使用指针。 – Kebeng
Go没有协变性。 –
@Kebeng我不介意在这里得到一个对象的副本,所以指针是没有必要的。并且让它们成为“同一类型”就是关键。 – xxorde