Golang快速初始化sql.Null*

huangapple go评论82阅读模式
英文:

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 &quot;fmt&quot;
import &quot;database/sql&quot;


type Something struct {
	Int64 int64
	Valid bool
}

func main() {
	var s = sql.NullInt64{1, true}  // &lt;- unkeyed fields warning
	var s1 = Something{1, true}
	fmt.Printf(&quot;Hello, %#v %#v\n&quot;, 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 vetgo.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.

huangapple
  • 本文由 发表于 2014年12月20日 18:16:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/27579205.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定