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 请问这个是什么意思?
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流
  • ¥15 Rstudio 保存代码闪退
  • ¥20 win系统的PYQT程序生成的数据如何放入云服务器阿里云window版?