## When Should You Use the `new` Keyword in Go?

Susan Sarandon
Release: 2024-10-25 05:30:02
Original
305 people have browsed it

## When Should You Use the `new` Keyword in Go?

The Use of new 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.

Primitive Language Constructs

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>
Copy after login

Structures

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.

Initialization Considerations

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.

Use Cases for new

Despite the limitations mentioned above, new has its uses in Go:

  • Initialization with Non-Zero Values: For structs with non-zero initial values, new can be convenient, allowing you to allocate a new struct and initialize its fields in a single step.
  • Private Fields or Interfaces: Wrapping the allocation in a function (e.g., NewMyStruct()) can hide private fields or instantiate an interface, allowing for better control over the structure and its accessibility.
  • Evolving Structures: Using new makes it easier to change the structure of a struct without affecting its existing users.

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!