使用字段名初始化结构体

初始化结构体时,几乎始终应该指定字段名称。现在由go vet强制执行。

//bad usage
k := User{"John", "Doe", true}

//good usage
k := User{
    FirstName: "John",
    LastName: "Doe",
    Admin: true,
}

在编写测试表时,如果结构体的字段少于三个,可以省略字段名称。例如:

tests := []struct{
  op Operation
  want string
}{
  {Add, "add"},
  {Subtract, "subtract"},
}

Last updated

Was this helpful?