Initializing String Pointers in Structs
Initializing a string pointer in a struct can be challenging, especially when you need the pointer to be nil when unset. The following code snippet demonstrates an attempt to initialize a struct with a default string pointer value:
type Config struct { Uri *string } func init() { var config = Config{ Uri: "my:default" } }
However, this code fails with the error:
cannot use "string" (type string) as type *string in field value
This error occurs because you cannot get the address (to point) of a constant value. To resolve this issue, you can define a variable and pass its address instead. Here's how:
type Config struct { Uri *string } func init() { v := "my:default" var config = Config{ Uri: &v } }
Now, the initialization succeeds because v is a variable whose address can be obtained using the & operator. This allows you to point the Uri field to a nil value when unset or to a specific string value when set.
The above is the detailed content of How to Initialize String Pointers in Go Structs?. For more information, please follow other related articles on the PHP Chinese website!