Home >Backend Development >Golang >## When Should You Use the `new` Keyword in Go?
When working with Go, it's essential to understand the appropriate usage of the new keyword. This article aims to shed light on specific situations where new is recommended, addressing common misconceptions and providing clear explanations.
As demonstrated in the example provided, new is not suitable for primitive types such as slices. In these cases, the make command should be used to initialize the slice or map. For example:
<code class="go">func main() { y := make([]float, 100) fmt.Printf("Len = %d", len(y)) // Output: Len = 100 }</code>
When working with structs, the choice between y := new(my_struct) and y := &my_struct depends on the intended use and code readability. Both options create a pointer to a newly allocated struct on the heap. However, new can be more explicit when allocating a pointer, while & is a more concise notation.
In Go, variables are initialized with their zero values by default. This means that primitive types like integers, floats, and Booleans are initialized to 0, whereas slices, maps, and structs are initialized with their respective nil values. The new keyword does not alter this behavior, so any allocated structs will still have their fields initialized to their zero values.
Despite the limitations mentioned above, new has its uses in Go:
The above is the detailed content of ## When Should You Use the `new` Keyword in Go?. For more information, please follow other related articles on the PHP Chinese website!