duanbai1974 2014-01-30 04:49
浏览 1619
已采纳

如何在Go中从interface {}变量中提取字符串?

I'm new to the Go language.

I'm making a small web application with Go, the Gorilla toolkit, and the Mustache template engine.

Everything works great so far.

I use hoisie/mustache and gorilla/sessions, but I'm struggling with passing variables from one to the other. I have a map[string]interface{} that I pass to the template engine. When a user is logged in, I want to take the user's session data and merge it with my map[string]interface{} so that the data becomes available for rendering.

The problem is that gorilla/sessions returns a map[interface{}]interface{} so the merge cannot be done (with the skills I have in this language).

I thought about extracting the string inside the interface{} variable (reflection?). I also thought about making my session data a map[interface{}]interface{} just like what gorilla/sessions provides. But I'm new to Go and I don't know if that can be considered best practice. As a Java guy, I feel like working with variables of type Object.

I would like to know the best approach for this problem in your opinion.

Thanks in advance.

  • 写回答

1条回答 默认 最新

  • doulao7998636570 2014-01-30 05:05
    关注

    You'll need to perform type assertions: specifically this section of Effective Go.

    str, ok := value.(string)
    if ok {
        fmt.Printf("string value is: %q
    ", str)
    } else {
        fmt.Printf("value is not a string
    ")
    }
    

    A more precise example given what you're trying to do:

    if userID, ok := session.Values["userID"].(string); ok {
         // User ID is set
    } else {
         // User ID is not set/wrong type; raise an error/HTTP 500/re-direct
    }
    
    type M map[string]interface{}
    
    err := t.ExecuteTemplate(w, "user_form.tmpl", M{"current_user": userID})
    if err != nil {
        // handle it
    }
    

    What you're doing is ensuring that the userID you pull out of the interface{} container is actually a string. If it's not, you handle it (if you don't, you'll program will panic as per the docs).

    If it is, you pass it to your template where you can access it as {{ .current_user }}. M is a quick shortcut that I use to avoid having to type out map[string]interface{} every time I call my template rendering function.

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

报告相同问题?

悬赏问题

  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程