dongyi6845 2019-08-12 08:35
浏览 237
已采纳

Golang是否会在修改/写入时复制字符串?

After reading the answer on Does Go language use Copy-on-write for strings , I feel the question was not adequately answered.

Given the example below, what is actually happening under the hood?

package main

import "fmt"

func main() {
  s := "Hello"
  t := s // t shares the same data as s
  s += "World" // a new string is created
  t += "There" // a new string is created.

  fmt.Printf("%s %s
", s, t)
}

output:

HelloWorld HelloThere

The question is when will golang determine there is a need to create a new copy?

  • 写回答

2条回答 默认 最新

  • dqz30992 2019-08-12 09:28
    关注

    In Go, string values are read-only byte slices and you cannot change its elements (immutable). Since it is a slice, it means that it has a backing (underlaying) array that has defined capacity. This being said, we can say that string is a data structure that points to a read-only backing array.

    Strings are optimized for high reusability and thus read-only. Whenever you modify a string a new string (byte slice) is created in the background which makes it a bit of costly operation. One recommendation is to convert a string to an actual byte slice []byte(string) and work with bytes or use strings.Builder when your program needs to do a lot of string manipulations.

    s := "Hello" // backing array for "hello" created; `s` points to the backing array
    t := s // `t` a new string structure and points to the same backing array as `s`, 
    s += "World" // new backing array created for "HelloWorld"; `s` points to the new backing array
    t += "There" // `t` was still pointing to "Hello" and with this operation, a new backing array is created for "HelloThere" and `t` points to it
    

    StringHeader - data structure

    String Data Type in GO

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 Web.config连不上数据库
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流
  • ¥15 Rstudio 保存代码闪退
  • ¥20 win系统的PYQT程序生成的数据如何放入云服务器阿里云window版?
  • ¥50 invest生境质量模块