Go Newbie question: I am trying to init the following struct, with a default value. I know that it works if "Uri" is a string and not pointer to a string (*string). But i need this pointer for comparing two instances of the struct, where Uri would be nil if not set, e.g. when i demarshal content from a json file. But how can I initialize such a struct properly as a "static default"?
type Config struct { Uri *string } func init() { var config = Config{ Uri: "my:default" } }
The code above fails with
cannot use "string" (type string) as type *string in field value
If you want to copy only pointer to the string, you can change the struct declaration as below and manually manage the memory for the string via functions Test_init and Test_delete . Show activity on this post.
The subscript specified inside the brackets is passed as an argument to the member function, which then returns the character at that position in the string. The name of a C++ string object is not a pointer and you can not use pointer notation with it or perform pointer arithmetic on it.
It's not possible to get the address (to point) of a constant value, which is why your initialization fails. If you define a variable and pass its address, your example will work.
type Config struct { Uri *string } func init() { v := "my:default" var config = Config{ Uri: &v } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With