我有一个范围超过的[] int。当我迭代时,我得到了一个键/值。我也想访问我正在迭代的切片。我不明白为什么切片会改变。
func main() {
var rows []string
rows = append(rows, "1 2 3", "4 5 6")
for _, row := range rows {
row := formatRow(row)
fmt.Println("sent row: ", row) // <------ THIS RETURNS [1,2,3]
for i, _ := range row {
fmt.Println("sent row: ", row) // <------ THIS RETURNS [1,3,3]
_ = getShortRow(row, i)
}
}
}
func getShortRow(row []int, i int) []int {
if i == 0 {
row := append(row[1:])
return row
}
endPosition := i + 1
if endPosition == len(row) {
row := append(row[:i])
return row
}
st := append(row[:i])
end := append(row[i+1:])
row = append(st, end...)
return row
}
func formatRow(row string) []int {
row = strings.Replace(row, " ", ",", -1)
if row[len(row)-1:] == "," {
row = row[:len(row)-1]
}
nValues := strings.Count(row, ",") + 1
var s []int
// convert []string to []int
for index := 0; index < nValues; index++ {
var value int
if index == nValues-1 {
value, _ = strconv.Atoi(row)
} else {
commaPosition := strings.Index(row, ",")
value, _ = strconv.Atoi(row[:commaPosition])
row = row[commaPosition+1:]
}
s = append(s, value)
}
return s
}
我无法弄清楚为什么切片值为[1,2,3]然后[1,2,3]然后[1,3,3]。似乎永远不会改变。