【问题标题】:Adding 2 array `type`s in Golang [duplicate]在Golang中添加2个数组`type`s [重复]
【发布时间】:2020-06-06 02:11:45
【问题描述】:

我有一个名为EmployeeListtype,它只是一个Employee 结构的数组。

如果我必须添加/组合 EmployeeList 对象,我想我可以按如下方式添加它们

package main

import (
  "fmt"
)

type Employee struct {
  Id      int    `json:"id"`
  Name string    `json:"name"`
}

type EmployeeList []Employee

func main() {
  listA := EmployeeList{
    Employee{Id: 1, Name: "foo"},
    Employee{Id: 2, Name: "bar"},
  }

  listB := EmployeeList{
    Employee{Id: 3, Name: "baz"},
  }

  // Print the combined lists
  fmt.Println(append(listA, listB))
}

但是append 抛出错误:

./prog.go:24:21: cannot use listB (type EmployeeList) as type Employee in append

我知道这与不匹配/意外类型有关,但我不确定如何将这两个列表添加在一起?

谢谢!

【问题讨论】:

  • 试试append(listA, listB...)

标签: arrays go struct


【解决方案1】:

您不能将EmployeeList 附加到Employee 的数组中。但是因为EmployeeList 被定义为Employee 的列表,所以您可以解压缩该数组并将其元素附加到listA。您可以使用... 解压阵列。

append(listA, listB...)

(参考类似答案https://stackoverflow.com/a/16248257/5666087

【讨论】:

  • 这是有道理的。我猜与 ruby​​ 中的 splat 运算符 *args 非常相似。谢谢!
猜你喜欢
  • 1970-01-01
  • 2016-06-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多