dongyirong3564 2016-07-16 19:43
浏览 49
已采纳

从golang中的函数返回结构片的正确模式

I'm relatively new to go and just trying to figure out what the right pattern is for returning a collection of structs from a function in go. See the code below, I have been returning a slice of structs which then gets problematic when trying to iterate over it since I have to use an interface type. See the example:

package main

import (
    "fmt"
)

type SomeStruct struct {
    Name       string
    URL        string
    StatusCode int
}

func main() {
    something := doSomething()
    fmt.Println(something)

    // iterate over things here but not possible because can't range on interface{}
    // would like to do something like
    //for z := range something {
    //    doStuff(z.Name)
    //}

}

func doSomething() interface{} {
    ServicesSlice := []interface{}{}
    ServicesSlice = append(ServicesSlice, SomeStruct{"somename1", "someurl1", 200})
    ServicesSlice = append(ServicesSlice, SomeStruct{"somename2", "someurl2", 500})
    return ServicesSlice
}

From what I have read, everything seems to use type switch or ValueOf with reflect to get the specific value. I think I'm just missing something here, as I feel passing data back and forth should be fairly straight forward.

  • 写回答

1条回答 默认 最新

  • douzhong6480 2016-07-16 19:49
    关注

    You just need to return the right type. Right now, you're returning interface{}, so you'd need to use a type assertion to get back to the actual type you want, but you can just change the function signature and return []SomeStruct (a slice of SomeStructs):

    package main
    
    import (
        "fmt"
    )
    
    type SomeStruct struct {
        Name       string
        URL        string
        StatusCode int
    }
    
    func main() {
        something := doSomething()
        fmt.Println(something)
    
        for _, thing := range something {
            fmt.Println(thing.Name)
        }
    }
    
    func doSomething() []SomeStruct {
        ServicesSlice := make([]SomeStruct, 0, 2)
        ServicesSlice = append(ServicesSlice, SomeStruct{"somename1", "someurl1", 200})
        ServicesSlice = append(ServicesSlice, SomeStruct{"somename2", "someurl2", 500})
        return ServicesSlice
    }
    

    https://play.golang.org/p/TdNQTYciTk

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

报告相同问题?

悬赏问题

  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计