7

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

11

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.