取字符串中字符的地址

问题描述:

package main
import (
    "fmt"
)
func main(){
    var str string = "hello,world"
    fmt.Println(&str)
    fmt.Println(&str[0])
}

I'm a complete rookie in golang. Just started learning for a few days. Here is my question:

compiled error: cannot take the address of str[0]

I searched <>, it says you can not take the address of character in a string, however I wonder why it is not allowed do this? Another confusion is that once you create a string, you cannot modify it anymore, does that mean the string is in constant space?

Yes this is correct in Go Documentation you can see that

A string type represents the set of string values. A string value is a (possibly empty) sequence of bytes. Strings are immutable: once created, it is impossible to change the contents of a string. The predeclared string type is string.

The length of a string s (its size in bytes) can be discovered using the built-in function len. The length is a compile-time constant if the string is a constant. A string's bytes can be accessed by integer indices 0 through len(s)-1. It is illegal to take the address of such an element; if s[i] is the i'th byte of a string, &s[i] is invalid.

I hope this will solve your doubts

To clarify the answer for future visitors to this question, accessing the address of the i-th byte of a string like &s[i] is invalid because strings are immutable. If you could get the address, then the string can be mutated.

The same logic applies to literal strings.

s := "stack overflow"
fmt.Println(&s) // works

fmt.Println(&"hello, world") // runtime error

This may seem strange, but it makes more sense if you think of it as a constant. For consistency, one would then have to allow taking the address of other constants, like &42 or &true.