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 shape_predictor_68_face_landmarks.dat
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制