Reference to string literals in Go

前端 未结 5 1122
忘了有多久
忘了有多久 2021-01-01 15:27

In my application I will frequently pass references to a static string. I wish to avoid having Go allocate memory for each call, but I failed to get the address to my string

5条回答
  •  轮回少年
    2021-01-01 16:15

    Taking the address of a literal (string, number, etc) is illegal because it has ambiguous semantics.

    Are you taking the address of the actual constant? Which would allow the value to be modified (and could lead to a runtime error) or do you want to allocate a new object, copy the constant over and get the address to the new version?

    This ambiguity does not exist in the case of test2 since you are dealing with an existing variable of which the semantics are clearly defined. The same would not work if the string was defined as const.

    The language spec avoids this ambiguity by explicitly not allowing what you are asking for. The solution is test2. While it is slightly more verbose, it keeps the rules simple and clean.

    Of course, every rule has its exceptions, and in Go this concerns composit literals: The following is legal and defined as such in the spec:

    func f() interface{} {
        return &struct {
            A int
            B int
        }{1, 2} 
    }
    

提交回复
热议问题