Initializing structs in Go

In Go, there are a few ways to initialize a new struct.

You can do this:

  • varStruct := &StructName{}
  • varStruct := StructName{}
  • varStruct := StructName{field1: "SomeValue", field2: 5,}
  • varStruct := new(StructName)
If you want to declare an uninitialized variable, declare it like so:

var varStruct StructName

Go is garbage collected, so there's no need to worry about memory release. After a variable falls out of scope, it'll be released some time in the future.

Published Thu, 24 May 2018 @ 12:51 AM by chuacw
Related articles: ,