當(dāng)嘗試將映射的 int 數(shù)組鍵添加到 int 切片切片時,范圍和使用arr[:]切片數(shù)組無法按預(yù)期工作。結(jié)果切片僅包含映射中“第一個”鍵的副本(注釋掉 for 循環(huán))。但是,將數(shù)組鍵復(fù)制到另一個變量并對新變量進(jìn)行切片是可行的,結(jié)果切片包含不同的映射鍵值。我想知道為什么需要復(fù)制。數(shù)組鍵不是k在每次迭代時從映射中復(fù)制為新數(shù)組嗎?我不知道在哪里可以找到有關(guān)此行為的文檔,并希望獲得鏈接和資源 :-)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[:])}
遍歷數(shù)組類型的映射鍵并對每個數(shù)組進(jìn)行切片為每次迭代提供相同的數(shù)組
慕碼人8056858
2022-06-21 16:51:42