Go: Structs explained

A struct is a typed collection of fields. It's useful for grouping data to form records.

Defining a struct

type Person struct {
    name string
    age  int
}

Using a struct

var x Person      // x is initialized to the zero value: Person{"", 0}
    x.name = "Alice"

    var px *Person    // px is initialized to nil
    px = new(Person)  // px points to the new struct Person{"", 0}
    px.name = "Bob"
    
    y := Person{       // y is initialized to Person{"Alice", 0}.
        name: "Alice",
    }
    
    py := &Person{     // py points to the new struct Person{"Bob", 8}.
        name: "Bob",
        age:  8,
    }
    
    z := Person{"Cecilia", 5} // One element for each field, in given order.

Comments

Be the first to comment!