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當然,它可以采用指向數組對象的指針,并就地修改數組,但這不太靈活,因為數組大小隨后會被烘焙到類型中。
- 1 回答
- 0 關注
- 163 瀏覽
添加回答
舉報