Create, initialize and compare structs

yourbasic.org/golang

Struct types

A struct is a typed collection of fields, useful for grouping data into records.

type Student struct {
	Name string
	Age  int
}

var a Student    // a == Student{"", 0}
a.Name = "Alice" // a == Student{"Alice", 0}

2 ways to create and initialize a new struct

The new keyword can be used to create a new struct. It returns a pointer to the newly created struct.

var pa *Student   // pa == nil
pa = new(Student) // pa == &Student{"", 0}
pa.Name = "Alice" // pa == &Student{"Alice", 0}

You can also create and initialize a struct with a struct literal.

b := Student{ // b == Student{"Bob", 0}
	Name: "Bob",
}
    
pb := &Student{ // pb == &Student{"Bob", 8}
	Name: "Bob",
	Age:  8,
}

c := Student{"Cecilia", 5} // c == Student{"Cecilia", 5}
d := Student{}             // d == Student{"", 0}

For further details, see The Go Language Specification: Composite literals.

Compare structs

You can compare struct values with the comparison operators == and !=. Two values are equal if their corresponding fields are equal.

d1 := Student{"David", 1}
d2 := Student{"David", 2}
fmt.Println(d1 == d2) // false

Go step by step

Core Go concepts: interfaces, structs, slices, maps, for loops, switch statements, packages.

Share this page: