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 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

    点赞 评论 复制链接分享

相关推荐