我有一个结构如下:
type Page struct {
title string
url string
}和一张结构图:
var mostViewed = make(map[int]Page)使用go-cache,我用TTL时间存储地图。
c.Set("data", mostViewed, 60*time.Minute) 但是,一旦我恢复了“数据”键,我如何才能把它放回地图上呢?
a, _ := c.Get("data")
fmt.Printf("%+v\n", a)
out: map[17:{title:xxx, url:yyy}]我试过这样的方法:
z := map[int]Page{a}有线索吗?这就像“重新映射”映射的字符串。
发布于 2017-05-16 19:35:24
您将得到一个interface{}类型,但您知道它是什么类型,所以您需要使用类型断言将其转换回一个map[int]Page。这里有一个快速的外部资源。https://newfivefour.com/golang-interface-type-assertions-switch.html
下面是一个例子
https://play.golang.org/p/lGseg88K1m
type Page struct {
title string
url string
}
func main() {
m := make(map[int]Page)
m[1] = Page{"hi", "there"}
iface := makeIface(m)
// use type assertion to cast it back to a map
if mapAgain, ok := iface.(map[int]Page); ok {
// it really is a map[int]Page
fmt.Printf("%+v\n", mapAgain)
} else {
// its not actually a map[int]Page
fmt.Println("oops")
}
// alternatively use a type-switch if it could be multiple types
switch v := iface.(type) {
case map[int]Page:
//yay
fmt.Printf("%+v\n", v)
case string:
// its a string
fmt.Println(v)
default:
// something we didn't account for
}
}
func makeIface(m map[int]Page) interface{} {
return m
}编辑:作为附带说明,您可能希望将地图类型设置为map[int]*Page,因为如果您这样做的话:
page := m[1]
page.url = "different"
fmt.Println(page) // prints url="different"
fmt.Println(m[1].url) // remains unchanged因为page将是地图中内容的副本,而不是映射本身中的Page。
https://stackoverflow.com/questions/44009786
复制相似问题