go - 附加到 []interface{} 问题——附加信息

标签 go

为了跟进我的最后一个问题,我再次尝试:

我创建了一个记录集合( 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/

相关文章:

go - 从父方法访问所有字段

json - 对嵌套结构使用自定义解码时,GoLang 结构无法正确解码

go - IBM Cloud Foundry Err:无法确定要安装的Go版本

go - fatal error : goroutines are asleep - deadlock

docker - Docker-compose拉出两个图像,一个应用程序,并且流畅,但没有日志发送到stdout进行流畅

sql - 使用golang返回mysql过程

Golang 保护(断言)函数命名约定

angular - 将 gRPC 与 Electron 14 结合使用

Golang,导入csv并将其转换为 map

for-loop - 在 n 秒后中断的循环