无法创建模拟谷歌云存储的界面



我正在尝试创建一个接口来抽象谷歌云存储。

我有以下接口:

type Client interface {
Bucket(name string) *BucketHandle
Close() error
}
type BucketHandle interface {
Create(context.Context, string, *storage.BucketAttrs) error
Delete(context.Context) error
Attrs(context.Context) (*storage.BucketAttrs, error)
}

和我的代码

type Bucket struct {
handler Client
}
func NewStorage(ctx context.Context, bucketName string) Bucket {
var bkt Bucket
client, err := storage.NewClient(ctx)
if err != nil {
return Bucket{}
}
bkt.handler = client
return bkt
}

我收到以下错误:cannot use client (variable of type *storage.Client) as Client value in assignment: wrong type for method Bucket

戈兰德显示以下内容

Cannot use 'client' (type *Client) as type Client Type does not implement 'Client' need method: Bucket(name string) *BucketHandle have method: Bucket(name string) *BucketHandle 

我不知道为什么类型不一样。

不能使用"客户端"(类型 *Client(作为类型 客户端类型 不 实现"客户端"需求方法:存储桶(名称字符串(*存储桶句柄有 方法:桶(名称字符串(*桶句柄

这个错误没有错。它看起来具有误导性的原因是,您创建了一个与库中的具体结构完全相同的接口,即BucketHandle

请注意两个函数中返回类型之间的差异:

// In your interface, the return type is an interface that you created
Bucket(name string) *BucketHandle
// In the library, the return type is a concrete struct that exists in that lib
Bucket(name string) *BucketHandle

您需要将Client界面修改为以下内容,它应该可以正常工作。

type Client interface {
Bucket(name string) *storage.BucketHandle
Close() error
}

storage.NewClient(ctx)返回*存储。客户。当您尝试分配给客户端时,您的客户端应实现存储的方法。客户端实现

客户端接口应为

type Client interface {
Close() error
ServiceAccount(ctx context.Context, projectID string) (string, error)
}

和桶可以是

type Bucket struct {
handler Client
}

查看此处 https://github.com/googleapis/google-cloud-go/blob/master/storage/storage.go#L101