Home >Backend Development >Golang >Why Return a Pointer Instead of a Value in Go's 'New' Function?

Why Return a Pointer Instead of a Value in Go's 'New' Function?

Susan Sarandon
Susan SarandonOriginal
2024-12-24 02:30:11536browse

Why Return a Pointer Instead of a Value in Go's

Understanding the Usage of Address Return in Go Constructors: New vs. Direct Return

Unlike other languages that provide explicit constructors, Go employs a "New" function in place of constructors. However, why is it common to return the address (&f) in Go's "New" func, rather than directly returning the File object?

Differences Between Address and Direct Returns

Go's syntax allows for returning either values (non-pointers) or pointers, leaving the decision to the developer. Typically, a pointer is returned when the value is more useful as one. This is especially the case if the returned value:

1. Has Multiple Methods with Pointer Receivers:

Returning a pointer allows for chaining method calls directly on the returned object, even if the methods take a pointer receiver. This eliminates the need to store the returned value in a variable and manually call the methods.

2. Is Stored in Non-Addressable Data Structures:

Some data structures, such as maps, do not support direct addressing of values. Returning a pointer circumvents this limitation, allowing for method calls on the value stored in the data structure.

3. Is a Large Struct Passed Around Frequently:

Pointers are advantageous for large structs that will be heavily passed around, as it optimizes memory usage and performance.

Example Comparison:

Consider a simple struct with a method that takes a pointer receiver:

type My int

func (m *My) Str() string { return strconv.Itoa(int(*m)) }

func createMy(i int) My { return My(i) }  // Direct return
func createMyPtr(i int) *My { return (*My)(&i) }  // Address return

When attempting to use the direct return value:

fmt.Println(createMy(12).Str())

An error occurs: "cannot call pointer method on createMy(12)". However, with the address return:

fmt.Println(createMyPtr(12).Str())

The method call succeeds without error.

Conclusion:

The decision of whether to return a pointer or value directly in Go's "New" func is based on the intended usage of the returned object. Pointers provide advantages when dealing with methods with pointer receivers, non-addressable data structures, or large structs that will be passed around frequently.

The above is the detailed content of Why Return a Pointer Instead of a Value in Go's 'New' Function?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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