tags:

views:

69

answers:

2

Hi! I've got two forms of struct declaration in the function scope. 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)
}
+3  A: 

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.

Jonathan Leffler
+2  A: 

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

newacct