如何理解go语言字符串不能修改

先来看一下官方对string的定义:

// string is the set of all strings of 8-bit bytes, conventionally but not
// necessarily representing UTF-8-encoded text. A string may be empty, but
// not nil. Values of string type are immutable.
type string string

golang里面字符串是不能修改的,但是,如何理解呢?
比如:

s:="hello"
s="world"
s=s+"wprld"

上面代码都能修改呀?是哪里理解不对吗?

最佳答案

可以这样理解: 原来是s:="hello",把他变为s="world",那么s的指向存储实际字符串的内存地址str变了。变为world的地址了,但是s自己本身的地址没有变

file

1年前 评论
讨论数量: 12

可以这样理解: 原来是s:="hello",把他变为s="world",那么s的指向存储实际字符串的内存地址str变了。变为world的地址了,但是s自己本身的地址没有变

file

1年前 评论
巴啦啦

跟Java中的字符串不可变一个意思

1年前 评论
bluememory (楼主) 1年前
巴啦啦 (作者) 1年前

哪看的说不能修改的

1年前 评论
bluememory (楼主) 1年前
已下线 1年前
bluememory (楼主) 1年前
bluememory (楼主) 1年前

说明理解的还不够透彻,继续加油

1年前 评论
bluememory (楼主) 1年前

不能修改指的是通过下标的方式进行操作。例如s[0] = "h"文章参考

1年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!