gpt4 book ai didi

go - 无法创建模拟 Google Cloud Storage 的接口(interface)

转载 作者:行者123 更新时间:2023-12-01 22:05:55 27 4
gpt4 key购买 nike

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

我有以下接口(interface):

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
goland 显示以下内容
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 

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

最佳答案

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



这个错误没有任何问题。它看起来具有误导性的原因是因为您创建了一个与库中的具体结构同名的接口(interface),即 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接口(interface)到以下,它应该可以正常工作。
type Client interface {
Bucket(name string) *storage.BucketHandle
Close() error
}

关于go - 无法创建模拟 Google Cloud Storage 的接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61841734/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com