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.
以上是如何使用字串指標初始化結構並允許 Nil 值?的詳細內容。更多資訊請關注PHP中文網其他相關文章!