附加到[]接口{}问题-附加信息
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了附加到[]接口{}问题-附加信息相关的知识,希望对你有一定的参考价值。
为了跟进我的最后一个问题,我再次尝试:
我创建记录的集合(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不是collection1,collection2
答案
切片是数组的视图。当您这样做时:
record = record[:0]
您没有创建新的空切片。您仍在使用基础数组,新切片将其视为长度为0的切片。将新元素追加到record
时,您将覆盖基础数组元素。
将上面的语句替换为:
record = make([]recordType,0)
或
record= []recordType
使用新的切片进行记录。
以上是关于附加到[]接口{}问题-附加信息的主要内容,如果未能解决你的问题,请参考以下文章