The new keyword in Golang
Overview
structs are user-defined data types and are used to store other data types such as variables of int or string type. Using the keyword new to initialize a struct in Golang gives the user more control over the values of the various fields inside the struct.
Usage
new returns a pointer to the struct. Each individual field inside the struct can then be accessed and its value can be initialized or manipulated.
Note: another way of instantiating a
structin Golang is by using the pointer address operator.
An example of the usage of the new keyword is shown below.
Example
package mainimport "fmt"// example struct declaredtype Person struct {name stringage intgender string}func main() {//new returns a pointer to an instance of Person structvar person1 = new(Person)//setting values of the fieldsperson1.name = "Anna"person1.age = 25person1.gender = "female"//printing person1fmt.Println(person1)}
More uses of the new keyword
Although commonly used to initialize structs, the new keyword can be used for any user-defined type.
Let’s look at another example:
package mainimport "fmt"//a slice variable with type int declaredtype mySlice []intfunc main() {//an instance of mySlice initialized using short variable declarationslice1 := new(mySlice)//adding data to slice1 by first creating a temporary variabletempSlice := append(*slice1, 1,2,3)slice1 = &tempSlicefmt.Println(slice1)}
Explanation
-
In line 5, we create a custom data type. It is a slice with
intdata type. -
In line 10, we initialize an instance of the type
mySliceusing thenewkeyword. -
In lines 13-14, we add data to the
slice1variable by first creating a temporary variable. Directly trying to add data toslice1using the built-in append function results in an error. Sincenewreturns a pointer to thestruct, the address oftempSliceis stored inslice1.