當嘗試將映射的 int 數組鍵添加到 int 切片切片時,范圍和使用arr[:]切片數組無法按預期工作。結果切片僅包含映射中“第一個”鍵的副本(注釋掉 for 循環)。但是,將數組鍵復制到另一個變量并對新變量進行切片是可行的,結果切片包含不同的映射鍵值。我想知道為什么需要復制。數組鍵不是k在每次迭代時從映射中復制為新數組嗎?我不知道在哪里可以找到有關此行為的文檔,并希望獲得鏈接和資源 :-)ansSlice := [][]int{}//ans is a map with [3]int key type/* For some reason, this doesn't work, and appends values from the same array to ansSlicefor k, _ := range ans { ansSlice = append(ansSlice, k[:])}*/// however, this worksfor k, _ := range ans { key := k ansSlice = append(ansSlice, key[:])}
遍歷數組類型的映射鍵并對每個數組進行切片為每次迭代提供相同的數組
慕碼人8056858
2022-06-21 16:51:42