首页 > 解决方案 > 在地图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

标签: go

解决方案


上的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 方法。


推荐阅读