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 驱动学习 环境部署中的问题
  • ¥15 【急】在线问答CNC雕刻机的电子电路与编程
  • ¥60 在mc68335芯片上移植ucos ii 的成功工程文件
  • ¥15 笔记本外接显示器正常,但是笔记本屏幕黑屏
  • ¥15 Python pandas
  • ¥15 蓝牙硬件,可以用哪几种方法控制手机点击和滑动
  • ¥15 生物医学数据分析。基础课程就v经常唱课程舅成牛逼
  • ¥15 云环境云开发云函数对接微信商户中的分账功能
  • ¥15 空间转录组CRAD遇到问题
  • ¥20 materialstudio计算氢键脚本问题