Maison >développement back-end >Golang >Comment initialiser une structure avec un pointeur de chaîne et autoriser des valeurs nulles ?
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.
Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!