duanchun2349 2019-01-23 13:30
浏览 64
已采纳

将结构体作为参数传递给函数,并返回相应结构体的切片

I am trying to write a function which can be used by different structs. The return of the function has to be a slice of the corresponding struct. Thus I need a function which accept a struct as a parameter and return a slice. My code somehow looks like this but I have no idea how can I wrap it as a function?

type name struct{
   FirstName string `xml:"firstName"`
   LastName string `xml:"lastName"`
  }

fileList := TreeTraversal(".")
    var a name
    var b []name 


for i := 0; i < len(fileList); i++{
    fileByte, _ := ioutil.ReadFile(fileList[i])

    xml.Unmarshal(fileByte, &a)
    b = append(b, a)
}

As far as I know I can pass a struct to a function as an interface, but I have no idea about the return type?

  • 写回答

1条回答 默认 最新

  • duangaoe9401 2019-01-23 14:07
    关注

    If you want a function that takes any struct type and returns a slice of it, like:

    func MakeSlice(s ANY_STRUCT_TYPE) []ANY_STRUCT_TYPE
    

    You're looking for generics, which Go doesn't currently support. See this FAQ entry.

    The Go team is working to add generics to the language - it's a work in progress, and everyone is free to participate in the discussion. Once generics exist, they will provide the solution you seek here.


    In the meantime, you could use code generation or think of a slightly different design for your problem. Some code duplication is OK too, Go doesn't frown upon it as badly as some other languages.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)