gpt4 book ai didi

go - 如何将结构分配给接口(interface)

转载 作者:IT王子 更新时间:2023-10-29 02:27:06 26 4
gpt4 key购买 nike

这是我的代码:

type ICacheEngine interface {
// ...
}

// implements all methods of ICacheEngine
type RedisCache struct { }

type ApplicationCache struct {
Cache *ICacheEngine
}

func NewRedisCache() *ApplicationCache {
appCache := new(ApplicationCache)
redisCache := new(RedisCache)
appCache.Cache = redisCache // here is an error : can not use *RedisCache as *ICacheEngine
return appCache
}

RedisCache实现了ICacheEngine的所有方法。我可以将 RedisCache 传递给获取 ICacheEngine 的方法:

func test(something ICacheEngine) *ICacheEngine {
return &something
}

....

appCache.Cache = test(redisCache)

但是我无法将 RedisCache 分配给 ICacheEngine。为什么 ?我怎样才能避免 test() 功能?当我将具体类型设置为接口(interface)并接下来调用它方法时,使用接口(interface)进行编程会是什么样子?

最佳答案

考虑到接口(interface)可以存储结构指向结构的指针,请确保将您的 ApplicationCache 结构定义为:

type ApplicationCache struct { 
Cache ICacheEngine
}

参见“Cast a struct pointer to interface pointer in Golang”。

关于go - 如何将结构分配给接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51074581/

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