为什么在Go语言中修改一个字符串并不会分配额外的空间?

egdjgwm8  于 2023-02-20  发布在  Go
关注(0)|答案(2)|浏览(81)

我是Go语言的新手,正在尝试理解字符串在Go语言中是如何工作的,我最大的疑问是,为什么在我的例子中将str从"black"改为"orange"而不改变str的地址,我注意到地址的改变是在使用str_cpy进行复制时。
先谢了。
代码:

func main(){
  // set str as Black
  var str string = "Black"
  log.Println("String is set to: ", str)
  log.Println("Current address of String is: ", &str)

  //set str as black
  log.Println("Testing Mutability...")
  slice := []rune(str)
  slice[0] = 'b'
  str = string(slice)
  log.Println("String after mutation is...", str)
  log.Println("Current address of String is: ", &str)
 
  //make a copy of str, str_cpy expected value: black
  str_cpy := str
  log.Println("StringCOPY is set to: ", str_cpy)
  log.Println("Current address of StringCOPY is: ", &str_cpy)

  //change str from black to Orange
  str = "Orange"
  log.Println("String now is...", str)
  log.Println("Current address of String is: ", &str)

  changeusingPointer(&str)
  log.Println("String was changed using pointer to: ", str)
  log.Println("Current address of String is: ", &str)
  
}

func changeusingPointer(s *string){
  log.Println("s points to ", s)
  *s = "White"
}

我得到的输出是:

2023/02/18 10:39:38 String is set to:  Black
2023/02/18 10:39:38 Current address of String is:  0xc000014060
2023/02/18 10:39:38 Testing Mutability...
2023/02/18 10:39:38 String after mutation is... black
2023/02/18 10:39:38 Current address of String is:  0xc000014060
2023/02/18 10:39:38 StringCOPY is set to:  black
2023/02/18 10:39:38 Current address of StringCOPY is:  0xc000014090
2023/02/18 10:39:38 String now is... Orange
2023/02/18 10:39:38 Current address of String is:  0xc000014060
2023/02/18 10:39:38 s points to  0xc000014060
2023/02/18 10:39:38 String was changed using pointer to:  White
2023/02/18 10:39:38 Current address of String is:  0xc000014060

我期望字符串str的地址在将其值从"black"更改为"orange"时也会更改。

9lowa7mx

9lowa7mx1#

字符串是包含两个元素的结构:指向包含字符串的数组的指针,以及字符串长度。因此,当您声明str="Orange"时,会发生如下情况:

str=internalString{ arr: <pointer to array "Orange">, len: 6}

当您为str指定一个新值(如“Black”)时,它将变为:

str=internalString{ arr: <pointer to array "Black">, len: 5}

str的地址不变。

jobtbby3

jobtbby32#

当你创建str_copy时,你复制了值,并把它放在别的地方,这样指针就应该改变了,但是当你改变str的值时,数组指针保持不变,只是值改变了

相关问题