PGene
PGene

Reputation: 442

Defining a struct with type vs. var keyword

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)
}

Upvotes: 3

Views: 365

Answers (2)

newacct
newacct

Reputation: 122419

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

Upvotes: 2

Jonathan Leffler
Jonathan Leffler

Reputation: 753445

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.

Upvotes: 3

Related Questions