How to initialise a struct in Go?

Technology CommunityCategory: GolangHow to initialise a struct in Go?
VietMX Staff asked 3 years ago

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}