2 回答

TA貢獻1744條經驗 獲得超4個贊
在 Go 中,字符串值是read-only
字節切片,您無法更改其元素(不可變)。由于它是一個切片,因此意味著它有一個已定義容量的支持(底層)數組。話雖這么說,我們可以說字符串是一個指向只讀后備數組的數據結構。
字符串針對高可重用性進行了優化,因此是只讀的。每當您修改字符串時,都會在后臺創建一個新字符串(字節切片),這使得操作成本較高。一項建議是將字符串轉換為實際的字節切片[]byte(string)
并使用字節,或者當程序需要執行大量字符串操作時使用strings.Builder 。
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

TA貢獻1846條經驗 獲得超7個贊
經過評論部分對此進行了大量辯論/討論后,這是我的結論。
Golang 沒有寫時復制。
這里的+=是顯式創建一個新字符串,相當于s = s + "World"創建一個新字符串并將其分配回s
如果你嘗試編寫以下代碼,由于 Golang 字符串的不可變性,將會導致編譯錯誤
t[0] = 'A' // cannot assign to t[0]
因此,Golang 中的所有內容都是顯式的,Golang 沒有隱式執行任何操作。這就是 Golang 中不存在寫時復制的原因。
注意:COW 和不變性并不相互排斥。
- 2 回答
- 0 關注
- 199 瀏覽
添加回答
舉報