1

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 ?

2 Answers 2

3

It's asking you to add the keys, e.g.

var s = sql.NullInt64{Int64: 1, Valid: true}
Sign up to request clarification or add additional context in comments.

2 Comments

Yes, but other structs with 1-2 elements i used to initialize without keys and just wondering what is different about this type, why it suddenly needs explicit keys
@Dfr: It doesn't need keys. go vet is suggesting that you use them to prevent possible errors (like renaming or reordering of the struct fields).
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.