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 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵