【发布时间】:2019-11-27 20:59:59
【问题描述】:
为了跟进我的最后一个问题,我再次尝试:
我创建了一个记录集合(map[string]string)
当我将两个不同的集合附加到接口切片时: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
【问题讨论】:
-
我建议您阅读this 以更好地了解切片的工作原理。这里还有一些与您的代码有关的评论play.golang.com/p/J_vWRsCd5rN
标签: go