There are objects in Go that have to be initialized, for example channels and slices immediately come to mind. You’ll have to call make
to set that up.
“The make built-in function allocates and initializes an object of type slice, map, or chan (only). Like new, the first argument is a type, not a value. Unlike new, make’s return type is the same as the type of its argument, not a pointer to it.”
关于constructor部分?
value receivers
1 | type Person struct { |
And to use such a constructor, you would invoke Person{}.New("Tit Petric")
and end up with the initialized object. We can in fact reason better about the code we are writing, because we can asume that we’ll end up with a Person
object (or a pointer to it), because that’s what we start with
there’s no performance or memory impact from using value receivers over usual function constructors
1 | New 2000000 754 ns/op 0 B/op 0 allocs/op |
原因在于:The constructor code is completely the same, and in both cases, the functions get fully inlined, so whichever format you prefer to write results in completely the same assembly code output
conclusion
While value receiver constructors do feel slightly awkward, it’s as close to analogous copy of constructors from other languages. While in PHP the constructor would be invoked when you call new Person(...)
and would only return objects of that type, Go actually allows you to go beyond that with Person{}.New()
.