【问题标题】:Appending to []interface{} problems --Additonal Info附加到 []interface{} 问题——附加信息
【发布时间】:2019-11-27 20:59:59
【问题描述】:

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

我创建了一个记录集合(ma​​p[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

【问题讨论】:

标签: go


【解决方案1】:

切片是数组的视图。当你这样做时:

record = record[:0]

您没有创建新的空切片。您仍在使用底层数组,新切片将其视为长度为 0 的切片。当您将新元素附加到 record 时,您正在覆盖底层数组元素。

将上述语句替换为:

record = make([]recordType,0)

record= []recordType{}

为记录使用新切片。

【讨论】:

  • 它是 make([]record, 0) 而不是 new(recordType,0)
  • 答案是在构建新集合时:set "record = nil" 这可以保证
  • 记录由新的追加语句初始化。现在我得到了所需的 db[0] collection1 和 db[1] collection2。感谢大家的帮助
猜你喜欢
  • 1970-01-01
  • 2021-06-06
  • 1970-01-01
  • 1970-01-01
  • 2012-12-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-10
相关资源
最近更新 更多