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

Printing value of sql.NullString in Go template

我从数据库中获取了详细信息,其中有几列属于 sql.NullStringsql.NullInt64 列。

现在,当我打印它们时,在检查它是否为 Valid 之后,它以 {3 true} 格式打印数据。我只想从中打印值 3

我怎样才能做到这一点?

目前是这样的,我正在打印:

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

sql.NullInt64 是一个结构:

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

打印结构值时,默认格式是您当前看到的格式。

如果您事先检查它是否有效且非 nil,您可以简单地打印仅包含数值的 NullInt64.Int64 字段。

您可以这样做:

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

查看这个简单的例子来测试它:

vs := []*sql.NullInt64{
    {3, true},
    {2, true},
}

t := template.Must(template.New("").Parse(
    "{{range .}}{{.Int64}}\n{{end}}",
))

if err := t.Execute(os.Stdout, vs); err != nil {
    panic(err)
}

输出(在 Go Playground 上尝试):

3
2