Answer the question
In order to leave comments, you need to log in
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
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)
type User struct {
Name string
Password []byte
}
func SetPassword(u *User) {
u.Password = []byte(...)
}
// или
func (u *User) GeneratePassword() {
u.Password = []byte(...)
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question