Inserting Missing value NOT working GoLang
我正在尝试插入一个int值,如果它不在其中,就进行切片。
我的代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | package main import ( "fmt" ) func AppendIfMissing(slice []int, i int) []int { for _, ele := range slice { if ele == i { fmt.Println(i) return slice } } fmt.Println("i value is", i) slice = append(slice, i) return slice } func main() { slice1 := []int{1, 2, 3, 4} AppendIfMissing(slice1, 60) fmt.Println("slice after adding :", slice1) } |
输出:
1 2 | i value is 60 slice after adding : [1 2 3 4] |
没有追加到切片。我的代码有什么问题?
- 最后还回来的
它需要影响到一个变量
1slice1 = AppendIfMissing(slice1, 60)
请参见游乐场示例。
我同意"数组、片(和字符串):
Even though the slice header is passed by value, the header includes a pointer to elements of an array, so both the original slice header and the copy of the header passed to the function describe the same array.
Therefore, when the function returns, the modified elements can be seen through the original slice variable.
但本文中的函数没有使用
1 2 3 4 5 | func AddOneToEachElement(slice []byte) { for i := range slice { slice[i]++ } } |
the contents of a slice argument can be modified by a function, but its header cannot
通过做
1 | slice = append(slice, i) |
修改头,将结果切片重新分配到完全不同的数组。这在函数之外是不可见的。