Golang basics struct and new() keyword

前端 未结 3 1704
Happy的楠姐
Happy的楠姐 2021-02-01 01:54

I was learning golang, and as I was going through the chapter that describes Structures, I came across different ways to initialize structures.

p1 := passport{}         


        
3条回答
  •  一整个雨季
    2021-02-01 02:38

    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.

提交回复
热议问题