Go语言指针类型字段赋值简写方式及代码简化方法咨询
Great question! You're right that declaring a separate variable just to take its address feels unnecessary—there are cleaner ways to assign a pointer field in Go. Let's walk through a couple of practical options depending on your Go version:
1. Directly take the address of a literal (Go 1.17+)
Starting in Go 1.17, you can take the address of a composite literal directly, which lets you skip the intermediate variable entirely. This is the most concise and readable approach for modern Go:
package main import "fmt" type test struct { A *int B string } func main() { // Option A: Initialize the struct all at once A := test{ B: "hello", A: &int{1}, // No separate x variable needed! } fmt.Printf("%s, %v", A.B, *A.A) // Option B: Assign fields individually if you prefer // var A test // A.B = "hello" // A.A = &int{1} }
2. Use the new function (compatible with all Go versions)
If you need to support older Go versions (pre-1.17), the new function allocates memory for a type and returns a pointer to it. You can then assign the value directly to the dereferenced pointer:
package main import "fmt" type test struct { A *int B string } func main() { var A test A.B = "hello" A.A = new(int) // Allocates an int and returns a *int *A.A = 1 // Set the value of the int the pointer points to fmt.Printf("%s, %v", A.B, *A.A) }
3. Compact temporary variable (if you prefer)
If you still want to use a temporary variable but keep it tight, you can declare and assign it in a single line (though this is slightly less clean than the first two options):
package main import "fmt" type test struct { A *int B string } func main() { var A test A.B = "hello" x := 1; A.A = &x // Single-line declaration and address assignment fmt.Printf("%s, %v", A.B, *A.A) }
For most cases, the first option (&int{1}) is the best choice—it's clean, avoids clutter, and aligns with modern Go idioms.
内容的提问来源于stack exchange,提问作者heretolearn

