doufu4333 2016-05-09 11:11
浏览 50
已采纳

将结构数组传递给Go中的函数

I have an object parsed from some XML file. It has struct type like this

type Report struct {
    Items []Item `xml:......`
    AnotherItems []AnotherItem `xml:......`
}
type Item struct {
    Name string
}
type AnotherItem struct {
    Name string
}
func (Item *Item) Foo() bool {
    //some code here
}
func (AnotherItem *AnotherItem) Foo() bool {
    //another code here
}

For each item i have to do smth like this:

func main(){
    //some funcs called to get the report object
    doSmth(report.Items)
    doSmth(report.AnotherItems)
}
func doSmth(items ????){
    for _, item : range items {
        item.Foo()
    }
}

Since i have different items with same function i want to have only one doSmth so i can't do just doSmth(items []Item) And the question is - what should i write instead of "????" to get this working? The only way i made it to pass report.Items into doSmth() was

func doSmth(items interface{})

But it throws me an error "cannot range over items (type interface {})" And if instead of iteration i just put smth like

func doSmth(items interface{}){
    fmt.Println(items)
}

program print the list of my items

  • 写回答

3条回答 默认 最新

  • duanben4771 2016-05-09 11:19
    关注

    Replace ???? with []Item: Go Playground. It is just the same as how that variable report.Items is defined in struct Report.

    Ok, yes that does change the question. The thing I thought of immediately was that you just needed to create an interface such as Itemer and have []Itemer in the function definition of doSmth:

    type Itemer interface {
        Foo() bool
    } 
    
    func doSmth(items []Itemer) {
        ...
    }
    

    Unfortunately this does not seem to be possible. I then tried some other permutations including using interface{}, []interface{} as well as variadic functions and I couldn't get anything to work.

    After doing some research it turns out that Go will not convert the type of slices. Even if each element of a slice is an instance of an interface such as Itemer or interface{} it still won't do it. I could not re-find the source but apparently This is due to the fact that a new slice would have to be created and each element would have to be type cast individually from the old slice to the new slice: https://stackoverflow.com/a/7975763/2325784.

    To me this suggests that a function such as doSmth is not possible.

    The only thing I could suggest is to restructure the code. If you are willing to post more information about Foo and doSmth I can try to help with that.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器