gpt4 book ai didi

go - 取字符串中某个字符的地址

转载 作者:IT王子 更新时间:2023-10-29 01:58:24 26 4
gpt4 key购买 nike

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

我是一个完全的 golang 菜鸟。刚开始学了几个天。这是我的问题:

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

我搜索了<<要走的路>>。它说你不能接受字符串中字符的地址。为什么不允许?

另一个困惑是,一旦你创建了一个字符串,你不能再修改了。这是否意味着字符串是常量空间?

最佳答案

是的,这在 Go 文档中是正确的,您可以看到

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.

希望能解决你的疑惑

关于go - 取字符串中某个字符的地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40926479/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com