dqjmq28248 2017-05-16 19:15
浏览 66
已采纳

Golang重映射接口Go-cache

I've got a struct like below:

type Page struct {
    title string
    url   string
}

and a map of structs:

 var mostViewed = make(map[int]Page)

With go-cache, I store the map with a TTL time.

c.Set("data", mostViewed, 60*time.Minute)    

But, once I recover "data" key, how could I assing it back to a map?

a, _ := c.Get("data")
fmt.Printf("%+v
", a)

out: map[17:{title:xxx, url:yyy}]

I tried something like:

 z := map[int]Page{a}

Any clue? It's like "remapping" a mapped string.

  • 写回答

1条回答 默认 最新

  • doutangu4671 2017-05-16 19:35
    关注

    You get an interface{} type back, but you know what it is, so you need to use a type assertion to cast it back to a map[int]Page. Here is a quick external resource. https://newfivefour.com/golang-interface-type-assertions-switch.html

    Here is an example

    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
    ", 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
    ", 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
    }
    

    Edit: as a side note, you probably want to make your map type map[int]*Page because if you did something like this:

    page := m[1]
    page.url = "different"
    fmt.Println(page) // prints url="different"
    fmt.Println(m[1].url) // remains unchanged
    

    Because page would be a copy of what is in the map, not the Page in the map itself.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?