I've got two forms of struct declaration in the function sc开发者_JS百科ope. As far as I could see the bellow-listed snippet woks just fine. The question is what's the difference between the two declaration ways? Is that only a semantic question or there is something tricky under the covers?
package main
import "fmt"
func main() {
type Person1 struct {
Name string
Id int
}
person1 := &Person1{Name : "John Smith", Id : 10}
fmt.Printf("(%s, %d)\n", person1.Name, person1.Id)
var person2 struct {
name string
id int
}
person2.name = "Kenneth Box"
person2.id = 20
fmt.Printf("(%s, %d)\n", person2.name, person2.id)
}
One is a named type - you can create multiple variables of that type, if you need to, using the type name.
The other type has no name. You cannot create more variables of the type other than by using the :=
operator.
person1
is a pointer to a struct, while person2
is a struct value itself. If you had done person1 := Person1{Name : "John Smith", Id : 10}
then it would be the same
精彩评论