-2

I have a struct which stores pointers like this

type Req struct {
    Name      *string
    Address   *string
    Number    string
}

I'm trying to create a variable with this struct type and assign values as follows

req := Req{
   Name = &"Alice"
   Address = &"ABCDEF"
   Number  = "123456"}

When I do this, I get the following error

invalid operation: cannot take address of "Alice" (untyped string constant)
invalid operation: cannot take address of "ABCDEF" (untyped string constant)

I'm not really clear on why this error is coming up and why "Alice" and "ABCDEF" are untyped string constants. I know I can assign the values to new vars and use the vars pointers in the req struct I'm using. But I'm trying to understand why my current approach is wrong. How can I make it work?

halfer
  • 19,824
  • 17
  • 99
  • 186
Sai Krishna
  • 593
  • 1
  • 8
  • 25
  • 1
    Pro-tip: questions are best phrased in terms of "How can I do X", "What do I need to do to achieve Y", etc. This is a phrasing that reflects personal agency i.e. that the speaker knows that their task is theirs to do. Conversely, "please help me" or "would someone help me with" may be interpreted as needy and lacking self-actualisation, and it can encourage downvotes. [This resource](https://meta.stackoverflow.com/questions/366264/how-can-we-encourage-new-authors-to-ask-confident-questions) may be useful related reading. – halfer May 25 '23 at 16:25

1 Answers1

1

Variables have addresses. Untyped constants are simply values, and they do not have addresses. You can get the address of a variable that is initialized using the untyped constant:

v:="Alice"
Name=&v

or, define a convenience function:

adr:=func(s string) *string {return &s}
req := Req{
   Name: adr("Alice"),
   Address: adr("ABCDEF"),
   Number: "123456",
}
Burak Serdar
  • 46,455
  • 3
  • 40
  • 59
  • And think about what it would mean if values _did_ have addresses. `foo := &"this constant is in the compiled binary" ; *foo = "does a longer string mean I get to overflow the array in my binary? DROP TABLE STUDENTS; --"` (or, if you want the constant to be lifted into the runtime: `foo := &"hello"; bar := &"hello"; *foo = "world"` -- now what's `bar`?) – yshavit May 25 '23 at 16:26