Golang basics struct and new() keyword

前端 未结 3 1706
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:36

    1. There is variable that holds the data yet. You can dereference the pointer using *pointerp2, and even assign it that to a variable (p2 := pointerp2), but this variable would be a copy of the data. That is, modifying one no longer affects the other (http://play.golang.org/p/9yRYbyvG8q).

    2. new tends to be less popular, especially with regard to structs. A good discussion of its purpose (hint: it came first) and use cases can be found at https://softwareengineering.stackexchange.com/a/216582.

    Edit: Also, p1 is not really a different kind of initialization from p3, but instead of assigning a value to any of the type's fields they are initialized to their zero value ("" for string, nil for []byte). The same would happen for any omitted fields:

    p4 := passport{
        Name: "Scott",
        Surname: "Adam",
    }
    

    In this case, p4.Photo and p4.DateOfBirth would still be zero-valued (nil and "" respectively). The passport{} case it just one where all the fields are omitted.

提交回复
热议问题