V
V
veryoriginalnickname2021-09-27 15:03:35
go
veryoriginalnickname, 2021-09-27 15:03:35

When to return a pointer when creating a structure?

When is a pointer returned when a structure is created, and when is the structure itself returned?

type ChtoTo struct {
 Value string
}

func NewOne(value string) *ChtoTo{
  return &ChtoTo{Value: value}
}

func NewTwo(value string) ChtoTo{
  return ChtoTo{Value: value}
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Evgeny Mamonov, 2021-09-27
@veryoriginalnickname

This can be determined by the following parameters:
- the size of the structure
- the frequency of "forwarding" this structure to other functions.
- the need to modify the structure inside the function
Structure
size when copying the structure, there will be no garbage collection overhead.
If the size of the structure is large, it is better to use a pointer, because when passing it as a parameter to other functions, 8 bytes will be copied (for 64-bit systems), and not the entire structure. Due to this, there will be a big performance gain, but there will be garbage collection overhead.
How often the structure is "thrown" into other functions.
If the structure is not large, but then it will be passed to many different functions - the overhead in this case will be greater than when passing just a pointer, in this case it is better to use a pointer.
Example:

s := SomeStruct{..}
func1(s)
func2(s)
...
func10(s)

In this case, the structure will be copied over the stack 10 times, one copy for each function call.
And if you pass it as a pointer, then only 8 bytes will be copied each time.
The need to modify the structure inside the
function in this case, the function will get a copy of the structure.
Example:
type User struct {
    Name string
    Password []byte
}
func SetPassword(u *User) {
    u.Password = []byte(...)
}
// или
func (u *User) GeneratePassword() {
    u.Password = []byte(...)
}

If you do not use a pointer here, no changes will occur in the original structure, because The function will change the copy of the structure.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question