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

时间:2016-07-16 19:43:18

标签: go

我相对较新,只是想弄清楚正确的模式是什么,从go中的函数返回一个结构集合。看到下面的代码,我一直在返回一些结构,然后在尝试迭代它时会出现问题,因为我必须使用接口类型。参见示例:

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
}

从我所看到的,一切似乎都使用type switch或ValueOf with reflect来获取特定值。我想我在这里错过了一些东西,因为我觉得来回传递数据应该是相当直接的。

1 个答案:

答案 0 :(得分:4)

您只需返回正确的类型即可。现在,你正在返回interface{},所以你需要使用一个类型断言来回到你想要的实际类型,但是你可以只改变函数签名并返回[]SomeStruct(a切片SomeStruct s):

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