亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Go 切片突變最佳實踐

Go 切片突變最佳實踐

Go
慕田峪7331174 2023-08-07 16:45:32
當切片傳遞時,很難預測底層原始數組是否正在發生變異,或者原始數組的副本是否正在發生變異a = [3]int {0, 1, 2}s = a[:]s[0] = 10a[0] == s[0] // trues = append(s, 3)s[0] = 20a[0] == s[0] // false假設今天我有這樣的處理a = [3]int {0, 1, 2}s = some_func(a[:]) // returns sliceprocess(s) // a is getting mutated because so far some_func hasn't caused the underlying array to be copied現在明天a = [3]int {0, 1, 2}s = some_func(a[:]) // returns slice, does append operationsprocess(s) // a is not getting mutated because some_func caused the underlying array to be copied那么切片的最佳實踐是什么?
查看完整描述

1 回答

?
蝴蝶刀刀

TA貢獻1801條經驗 獲得超8個贊

如果一個函數確實就地修改了切片的底層數組,并且承諾它總是就地修改底層數組,那么該函數通常應該按值獲取切片參數并且不返回更新的切片:1


// Mutate() modifies (the backing array of) s in place to achieve $result.

// See below for why it returns an int.

func Mutate(s []T) int {

    // code

}

如果函數可以就地修改底層數組,但可能返回使用新數組的切片,則該函數應返回新的切片值,或采用指向切片的指針:


// Replace() operates on a slice of T, but may return a totally new

// slice of T.

func Replace(s []T) []T {

    // code

}

當此函數返回時,您應該假設底層數組(如果您擁有它)可能正在使用,也可能沒有使用:


func callsReplace() {

    var arr [10]T

    s := Replace(arr[:])

    // From here on, do not use variable arr directly as

    // we don't know if it is s's backing array, or not.


    // more code

}

但Mutate()承諾會就地修改數組。請注意,Mutate通常需要返回實際更新的數組元素的數量:


func callsMutate() {

    var arr [10]T

    n := Mutate(arr[:])

    // now work with arr[0] through arr[n]


    // more code

}

1當然,它可以采用指向數組對象的指針,并就地修改數組,但這不太靈活,因為數組大小隨后會被烘焙到類型中。


查看完整回答
反對 回復 2023-08-07
  • 1 回答
  • 0 關注
  • 163 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號