dongren4758 2017-09-21 08:45 采纳率: 0%
浏览 419
已采纳

在Go模板中打印sql.NullString的值

I have fetched details from database where couple of column were of sql.NullString and sql.NullInt64 column.

Now, while I print them, after checking if it is Valid, it prints data in {3 true} format. I only want to print value 3 from it.

How can I achieve this?

Currently this is what, I am printing:

{{ range $value := .CatMenu }}
   ... // Other data
   {{ $value.ParentID }}  // This is sql.NullInt64 type
{{ end }}
  • 写回答

1条回答 默认 最新

  • douweng7233 2017-09-21 10:22
    关注

    sql.NullInt64 is a struct:

    type NullInt64 struct {
        Int64 int64
        Valid bool // Valid is true if Int64 is not NULL
    }
    

    When printing struct values, the default formatting is what you currently see.

    If you check if it is valid and non-nil prior, you can simply print the NullInt64.Int64 field only which holds the numerical value.

    This is how you can do it:

    {{ range $value := .CatMenu }}
       ... // Other data
       {{ $value.ParentID.Int64 }}  // This is sql.NullInt64 type
    {{ end }}
    

    See this simple example to test it:

    vs := []*sql.NullInt64{
        {3, true},
        {2, true},
    }
    
    t := template.Must(template.New("").Parse(
        "{{range .}}{{.Int64}}
    {{end}}",
    ))
    
    if err := t.Execute(os.Stdout, vs); err != nil {
        panic(err)
    }
    

    Output (try it on the Go Playground):

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

报告相同问题?

悬赏问题

  • ¥15 BDSBAS-B1C和B1C信号有什么不同
  • ¥15 在半圆平面内随机生成点坐标
  • ¥15 系统容量变化的几种多址方式TDMA, CDMA,FDMA,OFDMA 对比,应该给的是一个曲线 图,随着系统容量的增加,几种多址方式性能的对比 图,MATLAB程序仿真折线图
  • ¥15 用visual Studio 写c ++只运行上一个旧代码的运行结果是怎么回事
  • ¥15 系统容量变化的几种多址方式(TDMA,FDMA,OFDMA,CDMA)对比(相关搜索:曲线图)
  • ¥15 worldclim 历史及未来气候数据矫正
  • ¥15 ajax服务器不能下载
  • ¥15 运用c++和opencv实现二维码的识别和三维坐标的建立
  • ¥100 理想汽车的ADB为什么到了国外换了SIM就可以打开?
  • ¥15 k210烧入flash报错error:2005