How to initialize a pointer to a struct in Go?
Jul 23, 2025 am 03:16 AMIn Go language, there are two main ways to initialize structure pointers: 1. Use the new() function to initialize zero value; 2. Use the &Struct{} syntax to initialize and assign values. new() is suitable for cases where only zero values are required, while &Struct{} is more flexible and supports specifying field values during initialization. Both create pointers, but the latter is more commonly used and readable. In addition, depending on whether the original data needs to be modified, the appropriate initialization method should be selected to match the method recipient type.
In Go language, it is not difficult to initialize a pointer to a struct, but novices sometimes confuse several writing methods, resulting in the program behavior not as expected. The key is to understand the differences and applicable scenarios between new()
and &Struct{}
.

Initialize the structure pointer using new()
new()
is a built-in function in Go that can be used to allocate memory and return a pointer to that memory. When you create a struct pointer with new()
, it initializes each field of the struct to their zero value.
For example:

type Person struct { Name string Age int } p := new(Person)
In this way, p
is a pointer to Person
, its field Name
is an empty string, and Age
is 0.
advantage:

- Simple, suitable for situations where only zero value initialization is required.
shortcoming:
- If you want to customize the initial value of the field,
new()
is not very convenient.
Initialize and assign values using &Struct{}
A more common and flexible way is to use the &Struct{}
syntax directly, which creates a struct instance and returns a pointer to it. You can also assign initial values to fields directly in braces.
for example:
p := &Person{ Name: "Alice", Age: 30, }
This way you can specify the value of the field during initialization, and the syntax is clear, suitable for most practical development scenarios.
Notice:
- The field name must be the export field defined in the structure (i.e., the initial letter is capitalized), otherwise the value cannot be assigned outside the package.
- Be careful if only some fields are initialized, the rest will be filled with zero values.
When to use new()
and when to use &Struct{}
?
Generally speaking, unless you explicitly only need zero value initialization, it is more recommended to use &Struct{}
. Because it is more intuitive, it also supports assignment at initialization, with better readability and flexibility.
You can choose according to the following situations:
- Just need a default zero value? Use
new()
. - Want to set the initial value? Use
&Struct{}
. - Need partial initialization? Or use
&Struct{}
, remember to pay attention to the default value of the unassigned field.
Small details: The difference between initialization of structure pointers and values
Sometimes you will see someone writing:
p1 := Person{} p2 := &Person{}
The former is the value type of the structure, and the latter is the pointer type. In function argument transfer or method receiver, these two writing methods affect whether the original data is modified.
If the method you wrote is of the *Person
type, then use &Person{}
to match; if it is of Person
type, both are OK (because Go will automatically take references).
Therefore, when initializing the structure pointer, you should use subsequent usage scenarios to determine whether the pointer is needed.
Basically that's it. Initializing structure pointers is not difficult in Go, but it is prone to errors in details, especially the problem of field default values and pointer passing. Paying more attention can avoid many bugs.
The above is the detailed content of How to initialize a pointer to a struct in Go?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Go's switch statement will not be executed throughout the process by default and will automatically exit after matching the first condition. 1. Switch starts with a keyword and can carry one or no value; 2. Case matches from top to bottom in order, only the first match is run; 3. Multiple conditions can be listed by commas to match the same case; 4. There is no need to manually add break, but can be forced through; 5.default is used for unmatched cases, usually placed at the end.

In Go, to break out of nested loops, you should use labeled break statements or return through functions; 1. Use labeled break: Place the tag before the outer loop, such as OuterLoop:for{...}, use breakOuterLoop in the inner loop to directly exit the outer loop; 2. Put the nested loop into the function, and return in advance when the conditions are met, thereby terminating all loops; 3. Avoid using flag variables or goto, the former is lengthy and easy to make mistakes, and the latter is not recommended; the correct way is that the tag must be before the loop rather than after it, which is the idiomatic way to break out of multi-layer loops in Go.

Usecontexttopropagatecancellationanddeadlinesacrossgoroutines,enablingcooperativecancellationinHTTPservers,backgroundtasks,andchainedcalls.2.Withcontext.WithCancel(),createacancellablecontextandcallcancel()tosignaltermination,alwaysdeferringcancel()t

Use a dedicated and reasonably configured HTTP client to set timeout and connection pools to improve performance and resource utilization; 2. Implement a retry mechanism with exponential backoff and jitter, only retry for 5xx, network errors and 429 status codes, and comply with Retry-After headers; 3. Use caches for static data such as user information (such as sync.Map or Redis), set reasonable TTL to avoid repeated requests; 4. Use semaphore or rate.Limiter to limit concurrency and request rates to prevent current limit or blocking; 5. Encapsulate the API as an interface to facilitate testing, mocking, and adding logs, tracking and other middleware; 6. Monitor request duration, error rate, status code and retry times through structured logs and indicators, combined with Op

To correctly copy slices in Go, you must create a new underlying array instead of directly assigning values; 1. Use make and copy functions: dst:=make([]T,len(src));copy(dst,src); 2. Use append and nil slices: dst:=append([]T(nil),src...); both methods can realize element-level copying, avoid sharing the underlying array, and ensure that modifications do not affect each other. Direct assignment of dst=src will cause both to refer to the same array and are not real copying.

Gooffersfasterexecutionspeedduetocompilationtonativemachinecode,outperforminginterpretedlanguageslikePythonintaskssuchasservingHTTPrequests.2.Itsefficientconcurrencymodelusinglightweightgoroutinesenablesthousandsofconcurrentoperationswithlowmemoryand

InitializeaGomodulewithgomodinit,2.InstallgqlgenCLI,3.Defineaschemainschema.graphqls,4.Rungqlgeninittogeneratemodelsandresolvers,5.Implementresolverfunctionsforqueriesandmutations,6.SetupanHTTPserverusingthegeneratedschema,and7.RuntheservertoaccessGr

Go uses time.Time structure to process dates and times, 1. Format and parse the reference time "2006-01-0215:04:05" corresponding to "MonJan215:04:05MST2006", 2. Use time.Date(year, month, day, hour, min, sec, nsec, loc) to create the date and specify the time zone such as time.UTC, 3. Time zone processing uses time.LoadLocation to load the position and use time.ParseInLocation to parse the time with time zone, 4. Time operation uses Add, AddDate and Sub methods to add and subtract and calculate the interval.
