gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 01:44:36 25 4
gpt4 key购买 nike

我从数据库中获取了详细信息,其中有几列是 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

关于sql - 在 Go 模板中打印 sql.NullString 的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46339330/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com