英文:
Golang quick initialize sql.Null*
问题
这是一个工作正常的小代码片段:
package main
import "fmt"
import "database/sql"
type Something struct {
Int64 int64
Valid bool
}
func main() {
var s = sql.NullInt64{1, true} // <- unkeyed fields warning
var s1 = Something{1, true}
fmt.Printf("Hello, %#v %#v\n", s, s1)
}
但是 go vet
抱怨:
test.go:12: database/sql.NullInt64 composite literal uses unkeyed fields
问题是:为什么它在第12行抱怨,而在第13行却没有抱怨?
英文:
Here is small code snippet that workds well:
package main
import "fmt"
import "database/sql"
type Something struct {
Int64 int64
Valid bool
}
func main() {
var s = sql.NullInt64{1, true} // <- unkeyed fields warning
var s1 = Something{1, true}
fmt.Printf("Hello, %#v %#v\n", s, s1)
}
But go vet
complains:
test.go:12: database/sql.NullInt64 composite literal uses unkeyed fields
Question is: why it does complain on line 12 and does not complain on line 13 here ?
答案1
得分: 3
这是要求你添加键的示例,例如:
var s = sql.NullInt64{Int64: 1, Valid: true}
英文:
It's asking you to add the keys, e.g.
var s = sql.NullInt64{Int64: 1, Valid: true}
答案2
得分: 1
要理解这种行为,我们可以简单地查看go vet
在go.tools
存储库中的源代码。
在composite.go:46
中,它检查了复合字面量的类型。如果字面量是当前包的一部分,go vet
就不会对未标记键的值发出警告。
// A simple type name like t or T does not need keys either,
// since it is almost certainly declared in the current package
这个检查可能存在的原因是外部包可能会更改结构字段并破坏你的代码。标记键的字段可以减少这个问题的发生。
英文:
To understand this behavior, we can simply look at the source for go vet
in the go.tools
repository.
In composite.go:46
, it checks the type of the composite literal. If the literal is part of the current package, go vet
does not warn you about unkeyed values.
// A simple type name like t or T does not need keys either,
// since it is almost certainly declared in the current package
This check likely exists because an external package could change the struct fields and break your code. Keyed fields make this less of a problem.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论