2

I am playing with Go and facing the following question:

package main

import "fmt"

func main() {
    var arr [2]*string
    var s1 string = "hello"
    arr[0] = &s1
    arr[1] = &"world"   // can't compile
    fmt.Println(arr[0], arr[1])
    fmt.Println(arr)
}

After compiling the above code I got the next error:

prog.go:10: cannot take the address of "world"

What is the reason I cannot obtain the address of the string literal? And if it is possible how can I do that?

Note: I obtained the address of s1. Should I always introduce variables for literals to get back their addresses?

Mark
  • 5,994
  • 5
  • 42
  • 55
  • 2
    You cannot because literals are not addressable by the language spec. – Volker Dec 27 '15 at 11:20
  • 1
    If my understanding is correct, literals are hard-coded into the executable binary and therefore can not be referenced. – W.K.S Dec 27 '15 at 11:24
  • 1
    Related: [How do I do a literal *int64 in Go?](http://stackoverflow.com/questions/30716354/how-do-i-do-a-literal-int64-in-go) Same applies here just with `string` instead of `int64`. – icza Dec 27 '15 at 12:08

0 Answers0