[Golang actual combat] Explain why some fields in the structure use pointer types instead of value types

Problem Description

type LibraryConfig struct {
    
    
	Mode         string `mapstructure:"mode"`
	Port         int    `mapstructure:"port"`
	*LogConfig   `mapstructure:"log"`
	*MysqlConfig `mapstructure:"mysql"`
	*RedisConfig `mapstructure:"redis"`
}

Do you know or can explain why the pointer type is used in this structure to define the structure? I always passed it by before, this time I want to understand it and record it for the convenience of follow-up review

explain

First, the structure field type can be a value type or a pointer type

The reason for using a pointer to pass a structure is to avoid copying a large amount of data. When passing a structure as a value type, a complete copy operation will occur, including each field in the structure. If the structure is large or contains a large number of data, resulting in significant performance loss.
In contrast, using a pointer to pass a structure only needs to pass the address pointing to the structure without performing a real copy operation, which saves time and memory and is more efficient

At the same time, using the pointer can also realize the optionality of the structure field. By using the field of the pointer type, it can be set to nil to indicate that the field does not need to be used or does not provide a value, which is very useful in some scenarios.
Passing structs by pointer can improve performance and allow optional fields. However, if the struct is small or contains a small number of fields, passing it by value is fine because the copying overhead is relatively small. The choice of pointer passing or value type passing depends on the specific situation and needs.

Guess you like

Origin blog.csdn.net/weixin_54174102/article/details/131537842