go - 在地图golang中设置值,输入错误,不确定如何修复
问题描述
我正在尝试将 golang 中的键:值对设置为本地缓存。
当我设置一个新对时,由于条目值的结构,我收到一个错误。
type Cache struct {
cache map[string]*entry
}
type entry struct {
value string
err error
}
func NewCache() *Cache {
return &Cache{cache: make(map[string]*entry)}
}
func (c *Cache) Set(key string, value *entry) (string, string) {
c.cache[key] = value
return key, value
}
我可以看到值对需要错误和值类型输出,但是如果有意义的话,我对如何在使用该错误值时设置值感到困惑?
更新包括获取功能,
func (c *Cache) Get(key string) (string, error) {
res, ok := c.cache[key]
if !ok {
res = &entry{}
// res.value, res.err = f()
c.cache[key] = res
}
return res.value, res.err
我错过了什么 - 任何指针表示赞赏。
我的意图是能够将值字符串从条目传递到地图中,本质上。
我已经开始重新编写一个更小的版本,但我认为如果我能让 Set 功能工作,这种格式是有意义的:S
解决方案
上的Set
方法Cache
声明了返回值(string, string)
,但是你返回key, value
,第一个是字符串,第二个是类型*entry
,不是string
。要解决这个问题,要么返回 astring
作为第二个返回值,要么将第二个声明的返回类型更改为*entry
.
给定变量名称value
(type *entry
) 和类型上的value
(type string
) 字段entry
,不清楚这里期望的行为是什么。但是,由于entry
是私有类型,我猜您实际上并不希望将类型的值传递*entry
给公共Set
方法。
也许这就是你所追求的:
func (c *Cache) Set(key string, value string, err error) (string, string) {
c.cache[key] = &entry{value, err}
return key, value
}
但也许你的意思是:
func (c *Cache) Set(key string, ent *entry) (string, *entry) {
c.cache[key] = ent
return key, ent
}
尽管在任何一种情况下,返回值似乎都是不必要的,因为它们与给定值相同。您可以考虑Set
改为使用 void 方法。
推荐阅读
- dart - Flutter:固定高度的响应式设计
- java - 程序控制不会出现在 Java 中的 else if 条件下
- php - 在我的路线某处遇到问题。拉拉维尔
- javascript - 使用 GSAP 制作的动画循环
- javascript - 如何将 node 模块与 chrome 扩展集成
- python - Python - 寻找一种更有效的方法来重新编号我的字典中的键
- amazon-web-services - 如何获取 Amazon S3 HTTP 请求的签名?
- javascript - 如何在不重新加载页面生效的情况下应用此 AJAX 请求?
- javascript - 观看多个属性不起作用Angular js
- c++ - 如何在另一个类中使用类成员的正确方法?