Golang: New Keyword

In Golang there are several ways to create instance of struct.

Say we have this Person struct:

type Person struct {
	name string
	age int
}

We can instantiate this struct with:

ryan := Person{}
// will return => { 0}
//			   => {name: age:0}

ryan := Person{name: "Ryan", age: 22}
// will return => {Ryan 22}

ryan := new(Person)
// will return => &{ 0}

When using the new keyword you will get reference of the struct in return.

References:


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *