Value Initialization in Go
In Go, using & to initialize a value versus using new() may seem like different approaches, but their functionality is essentially the same.
Illustrating the Equivalence
Consider the following code snippets:
v := &Vector{}
and
v := new(Vector)
Here, Vector represents a custom type. Both approaches allocate memory for the Vector struct and return a pointer to the allocated memory.
To demonstrate this equivalence, let's compare the resulting types:
package main import "fmt" import "reflect" type Vector struct { x int y int } func main() { v := &Vector{} x := new(Vector) fmt.Println(reflect.TypeOf(v)) fmt.Println(reflect.TypeOf(x)) }
Output:
*main.Vector *main.Vector
As видно, both methods yield pointers to the Vector type.
Historical Background and Preference
While both methods achieve the same result, their respective histories may influence developer preference. new() was introduced earlier in Go's development and was the only way to initialize pointers to basic types like integers. Since then, & has been added as a more general approach that works for any type.
Conclusion
Ultimately, the choice between & and new() is a matter of preference. Both approaches allocate memory and return a pointer to the allocated memory, resulting in identical functionality.
The above is the detailed content of Go Initialization: `&` vs. `new()`: What's the Difference?. For more information, please follow other related articles on the PHP Chinese website!