Home > Backend Development > Golang > Go Initialization: `&` vs. `new()`: What's the Difference?

Go Initialization: `&` vs. `new()`: What's the Difference?

Patricia Arquette
Release: 2024-12-18 14:47:10
Original
188 people have browsed it

Go Initialization:  `&` vs. `new()`: What's the Difference?

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

and

v := new(Vector)
Copy after login

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

Output:

*main.Vector
*main.Vector
Copy after login

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!

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