英文:
How do I convert this cache item back to a slice of maps?
问题
我对Go还不太熟悉,正在尝试使用Beego的缓存。我可以将[]map[string]string放入缓存中,但是无法弄清楚如何将值转换回[]map[string]string。
例如,将项目放入缓存中:
m := make([]map[string]string)
// 向映射切片添加项目
.......
// 将其缓存起来
if err := c.Put("key", m, 100); err != nil {
fmt.Println(err)
}
// 检索它
n := c.Get("key")
fmt.Println(reflect.TypeOf(n)) // ==> string
// 尝试失败
a := n.([]map[string]string)
fmt.Println(a) // 报错:接口转换:接口是字符串,而不是[]map[string]string
如何将n转换为映射切片?
英文:
I'm still new to Go and trying to use Beego's cache. I can put a []map[string]string into the cache but can't figure out how to convert the value back to a []map[string]string.
For instance, to put the item in the cache:
m:=make([]map[string]string)
// add items to the slice of maps
.......
// cache it
if err := c.Put("key", m, 100); err != nil {
fmt.Println(err)
}
// retrieve it
n := c.Get("key")
fmt.Println(reflect.TypeOf(n)) // ==>string
// failed attempt
a := n.([]map[string]string)
fmt.Println(a) // panic: interface conversion: interface is string, not []map[string]string
How do I convert n to a slice of maps?
答案1
得分: 2
深入研究代码后发现,即使代码中使用了interface{}
,实际上它会将所有内容压缩成[]byte
类型。
在执行Get
操作时,它会将所有内容转换为string
类型。
因此,你需要自己对数据结构进行编组/解组。
请参考以下示例,并将你的调用和错误检查替换为提供的示例代码:
package main
import (
"bytes"
"encoding/json"
"log"
)
var cache map[string]string = make(map[string]string)
func Put(key, value string) {
cache[key] = value
}
func Get(key string) string {
return cache[key]
}
func main() {
m := map[string]string{
"A": "1",
"B": "2",
}
if b, err := json.Marshal(m); err != nil {
log.Fatal(err)
} else {
Put("myKey", string(b))
}
b := bytes.NewBufferString(Get("myKey"))
var mm map[string]string
if err := json.Unmarshal(b.Bytes(), &mm); err != nil {
log.Fatal(err)
}
log.Printf("%#v", mm)
}
希望对你有所帮助!
英文:
well digging into the code seems like even if it says interface{} what it does it actually squash everything to []byte
https://github.com/astaxie/beego/blob/master/cache/memcache/memcache.go#L77
and when it Does the Get
convert everything to string
https://github.com/astaxie/beego/blob/master/cache/memcache/memcache.go#L61
So you need to Marshal / Unmarshal the data structure yourself.
See this example and substitute your calls and error check with the dummies one provided:
http://play.golang.org/p/9z3KcOlgAx
package main
import (
"bytes"
"encoding/json"
"log"
)
var cache map[string]string = make(map[string]string)
func Put(key, value string) {
cache[key] = value
}
func Get(key string) string {
return cache[key]
}
func main() {
m := map[string]string{
"A": "1",
"B": "2",
}
if b, err := json.Marshal(m); err != nil {
log.Fatal(err)
} else {
Put("myKey", string(b))
}
b := bytes.NewBufferString(Get("myKey"))
var mm map[string]string
if err := json.Unmarshal(b.Bytes(), &mm); err != nil {
log.Fatal(err)
}
log.Printf("%#v", mm)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论