Initializing a String Pointer in a Go Struct
In Go, structs can contain pointers to other values, including strings. While it's straightforward to initialize strings directly in structs, initializing string pointers can present a challenge.
Problem
When attempting to initialize a struct with a string pointer (*string) as a default value, an error occurs:
cannot use "string" (type string) as type *string in field value
Solution
To initialize a string pointer in a struct, you can't directly assign a constant string value to it. Instead, create a variable, assign the value to it, and then pass the variable's address to the string pointer:
type Config struct { Uri *string } func init() { v := "my:default" var config = Config{ Uri: &v } }
By using the & operator, you obtain the address of the variable (&v), which can then be assigned to the string pointer. This enables the comparison of two struct instances where Uri can be nil if not set.
以上是如何在 Go 结构体中初始化字符串指针?的详细内容。更多信息请关注PHP中文网其他相关文章!