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
.
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
struct
in Golang is by using the pointer address operator.
An example of the usage of the new
keyword is shown below.
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)}
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)}
In line 5, we create a custom data type. It is a slice with int
data type.
In line 10, we initialize an instance of the type mySlice
using the new
keyword.
In lines 13-14, we add data to the slice1
variable by first creating a temporary variable. Directly trying to add data to slice1
using the built-in append function results in an error. Since new
returns a pointer to the struct
, the address of tempSlice
is stored in slice1
.