Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Right pattern for returning slice of structs from function in golang

Tags:

go

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.

like image 847
lutix Avatar asked Jul 16 '16 19:07

lutix


1 Answers

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

like image 199
user94559 Avatar answered Nov 15 '22 07:11

user94559