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

lut*_*tix 3 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
}
Run Code Online (Sandbox Code Playgroud)

从我所阅读的内容来看,所有内容似乎都使用type switch或ValueOf与reflect来获取特定值。我认为我只是在这里遗漏了一些东西,因为我觉得来回传递数据应该很简单。

use*_*559 5

您只需要返回正确的类型。现在,您正在返回interface{},因此您需要使用类型断言来返回所需的实际类型,但是您只需更改函数签名并返回[]SomeStruct(一片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
}
Run Code Online (Sandbox Code Playgroud)

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