Home >Backend Development >Golang >How to Initialize a String Pointer in a Go Struct?
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.
The above is the detailed content of How to Initialize a String Pointer in a Go Struct?. For more information, please follow other related articles on the PHP Chinese website!