2016-07-16 19:43
浏览 49


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 (

type SomeStruct struct {
    Name       string
    URL        string
    StatusCode int

func main() {
    something := doSomething()

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

图片转代码服务由CSDN问答提供 功能建议

我相对较新,只想弄清楚什么是返回结构体集合的正确模式 从功能中去。 参见下面的代码,我一直在返回一个结构片,然后在尝试对其进行迭代时会出现问题,因为我必须使用接口类型。 请参见示例:

“ fmt” 
type SomeStruct struct {
  StatusCode int 
func main(){
 something:= doSomething()
 //遍历此处的内容,但由于无法在接口上进行范围{  } 
 // doStuff(z.Name)
func doSomething()接口 {} {
 ServicesSlice:= [] interface {} {} 
 ServicesSlice = append(ServicesSlice,SomeStruct {“ somename1”,“ someurl1”,200})
 ServicesSlice = append(ServicesSlice,SomeStruct {“ somename2”,  “ someurl2”,500})

从我阅读的内容来看,所有内容似乎都使用type switch或ValueOf并带有反射来获取 具体值。 我认为我只是在这里丢失了一些东西,因为我觉得来回传递数据应该很简单。

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

1条回答 默认 最新

相关推荐 更多相似问题