Golang basics struct and new() keyword

new allocates zeroed storage for a new item or type whatever and then returns a pointer to it. I don’t think it really matters on if you use new vs short variable declaration := type{} it’s mostly just preference

As for pointer2, the pointer2 variable holds its own data, when you do

// initializing a zeroed 'passport in memory'
pointerp2 := new(passport)
// setting the field Name to whatever
pointerp2.Name = "Anotherscott"

new allocates zeroed storage in memory and returns a pointer to it, so in short, new will return a pointer to whatever you’re making that is why pointerp2 returns &{ Anotherscott }

You mainly want to use pointers when you’re passing a variable around that you need to modify (but be careful of data races use mutexes or channels If you need to read and write to a variable from different functions)

A common method people use instead of new is just short dec a pointer type:

blah := &passport{}

blah is now a pointer to type passport

You can see in this playground:

http://play.golang.org/p/9OuM2Kqncq

When passing a pointer, you can modify the original value. When passing a non pointer you can’t modify it. That is because in go variables are passed as a copy. So in the iDontTakeAPointer function it is receiving a copy of the tester struct then modifying the name field and then returning, which does nothing for us as it is modifying the copy and not the original.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)