Reputation: 33
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 problem:
compiled error: cannot take the address of str[0]
I searched <<the way to go>>. It says you cannot take the address of a character in a string. Why is it not allowed?
Another confusion is that once you create a string, you cannot modify it anymore. Does that mean the string is in constant space?
Upvotes: 2
Views: 2414
Reputation: 1
builtin type string, its underlying struct is reflect.StringHeader
reflect.StringHeader.Data(uinptr), is string content memory address
try this:
(*reflect.StringHeader)(unsafe.Pointer(strPtr)).Data
Upvotes: 0
Reputation: 1070
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
.
Upvotes: 1
Reputation: 1827
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
Upvotes: 4