Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

initialize string pointer in struct [duplicate]

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 
like image 459
Mandragor Avatar asked Mar 04 '17 10:03

Mandragor


People also ask

How do you copy a struct to a string?

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.

Can we create string pointer in C++?

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.


1 Answers

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 } } 
like image 62
Nadh Avatar answered Oct 13 '22 08:10

Nadh