Initializing String Pointers in Structs
In Go, initializing a struct with a pointer to a string where the pointer can be nil requires careful handling. The following code snippet exemplifies the challenge:
type Config struct { Uri *string } func init() { var config = Config{ Uri: "my:default" } }
This fails with the error:
cannot use "string" (type string) as type *string in field value
To resolve this, one cannot simply point to a constant string value as in the above code. Instead, a variable is needed:
type Config struct { Uri *string } func init() { v := "my:default" var config = Config{ Uri: &v } }
In this code, the variable v is created and initialized with the desired value. Then, the address of v (i.e., &v) is assigned to the Uri field of the struct. This works because the Uri field is a pointer to a string, and the address of v is of type *string.
The above is the detailed content of How to Initialize String Pointers in Structs in Go?. For more information, please follow other related articles on the PHP Chinese website!