DevilKing's blog

冷灯看剑,剑上几分功名?炉香无需计苍生,纵一穿烟逝,万丈云埋,孤阳还照古陵

0%

Constructors In Go

原文链接

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
2
3
4
5
6
7
type Person struct {
name string
}

func (Person) New(name string) *Person {
return &Person{name}
}

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
2
New         2000000     754 ns/op     0 B/op      0 allocs/op
Person.New 2000000 786 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().