Home > Article > Backend Development > How to Initialize a Struct with a String Pointer and Allow for Nil Values?
Struct Pointer Initialization
Initializing a struct with a string pointer can be tricky, especially when the default value should be nil.
Problem
When attempting to initialize a struct with a string pointer as a default value, using a constant string in the initialization, an error occurs:
cannot use "string" (type string) as type *string in field value
Solution
To initialize a struct with a string pointer that can be nil, you must assign the address of a variable, not a constant value, to the pointer. Here's a modified code that works:
type Config struct { Uri *string } func init() { v := "my:default" var config = Config{ Uri: &v } }
In this case, the variable v holds the default string value. By taking its address using the & operator and assigning it to Uri, we're creating a string pointer that can be used for comparisons and can be nil if not explicitly set.
The above is the detailed content of How to Initialize a Struct with a String Pointer and Allow for Nil Values?. For more information, please follow other related articles on the PHP Chinese website!