- Joined
- Jun 30, 2023
Ooh, don't even fucking get me started lol.Pike then decided to add 5 different ways to allocate an object in Go.
For those who don't know Go, here's an example:
C-like:
type SomeType struct {
// struct fields here
}
C-like:
func NewSomeType() *SomeType {
x := SomeType{}
return &x
}
C-like:
func NewSomeType() *SomeType {
x := &SomeType{}
return x
}
C-like:
func NewSomeType() *SomeType {
x := new(SomeType) // returns pointer, like &SomeType.
return x
}
An important thing to note here is Go initializes type/struct fields to 0 automatically upon alloc. Effective Go (a very old spec-related article) says that
new(SomeType) and &SomeType{} are equivalent until you use the latter form to initialize non-zero values in the declaration.There's no clear distinction between stack and heap allocations when returning like you would normally have C. So whether you should use the 1st or 2nd/3rd form to return a pointer to a type is a matter of intense debate to this day. As much as I love Go, I have no fucking clue why they don't have a clear distinction between the first two forms, at the very least.
