为了跟进我的最后一个问题,我再次尝试:
我创建了一个记录集合( map[string]string )
当我将两个不同的集合附加到接口(interface) slice 时: var db []接口(interface){}
我期望的是 db[0] collection1 和 db[1] collection2
我得到的是 db[0] collection2 和 db[1] collection2
以下是激活码:
record = append(record, newWorkDataItem("FWC", d, "Left", "---", "10", "12.5"))
record = append(record, newWorkDataItem("FWC", d, "Left", "---", "10", "12.5"))
fmt.Println("Record 1: ", record)
db = append(db, record)
fmt.Println("Database1 = ", db)
record = record[:0]
fmt.Println("Record: ", record)
record = append(record, newWorkDataItem("FWT", d, "Left", "---", "15", "12.5"))
record = append(record, newWorkDataItem("FWT", d, "Right", "---", "15", "12.5"))
fmt.Println("Record 2: ", record)
db = append(db, record)
fmt.Println("Database2 = ", db)
fmt.Println("db[0] ", db[0])
fmt.Println("db[1] ", db[1])
以下是结果:
Record 1: [map[Data:11 27 2019 Exercise:FWC Notes:--- Reps:10 Side:Left Weight:12.5] map[Data:11 27 2019 Exercise:FWC Notes:--- Reps:10 Side:Left Weight:12.5]]
Database1 = [[map[Data:11 27 2019 Exercise:FWC Notes:--- Reps:10 Side:Left Weight:12.5] map[Data:11 27 2019 Exercise:FWC Notes:--- Reps:10 Side:Left Weight:12.5]]]
Record: []
Record 2: [map[Data:11 27 2019 Exercise:FWT Notes:--- Reps:15 Side:Left Weight:12.5] map[Data:11 27 2019 Exercise:FWT Notes:--- Reps:15 Side:Right Weight:12.5]]
Database2 = [[map[Data:11 27 2019 Exercise:FWT Notes:--- Reps:15 Side:Left Weight:12.5] map[Data:11 27 2019 Exercise:FWT Notes:--- Reps:15 Side:Right Weight:12.5]] [map[Data:11 27 2019 Exercise:FWT Notes:--- Reps:15 Side:Left Weight:12.5] map[Data:11 27 2019 Exercise:FWT Notes:--- Reps:15 Side:Right Weight:12.5]]]
db[0] [map[Data:11 27 2019 Exercise:FWT Notes:--- Reps:15 Side:Left Weight:12.5] map[Data:11 27 2019 Exercise:FWT Notes:--- Reps:15 Side:Right Weight:12.5]]
db[1] [map[Data:11 27 2019 Exercise:FWT Notes:--- Reps:15 Side:Left Weight:12.5] map[Data:11 27 2019 Exercise:FWT Notes:--- Reps:15 Side:Right Weight:12.5]]
如您所见,通过将新集合附加到“db”似乎不仅覆盖了第一个集合,然后附加了新集合。
所以我们得到collection2,collection2 NOT collection1,collection2
最佳答案
slice 是数组的 View 。当你这样做时:
record = record[:0]
您没有创建新的空 slice 。您仍在使用底层数组,新 slice 将其视为长度为 0 的 slice 。当您将新元素附加到
record
时,您正在覆盖底层数组元素。将上述语句替换为:
record = make([]recordType,0)
或者
record= []recordType{}
为记录使用新 slice 。
关于go - 附加到 []interface{} 问题——附加信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59078356/