dpbz14739
2015-10-09 06:29
浏览 860
已采纳

如何在golang中创建对象数组?

I have a requirement in which I need to store array of objects in a variable. The objects are of different types. Refer to following example:

 v := [ {"name":"ravi"},
        ["art","coding","music","travel"],
        {"language":"golang"},
        {"experience":"no"}
      ]

Notice the second element is array of string itself. After research, I thought of storing this as interface type like:

 var v interface{} = [ {"name":"ravi"},
                       ["art","coding","music","travel"],
                       {"language":"golang"},
                       {"experience":"no"}
                     ]

Still, I am getting few compilation errors which I am not able to find out.

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

我有一个要求,我需要在变量中存储对象数组。 对象是不同类型的。 请参考以下示例:

  v:= [{“ name”:“ ravi”},
 [“ art”,“ coding”,“ music”,“ travel  “],
 {” language“:” golang“},
 {” experience“:” no“} 
] 
   
 
 

注意第二个元素 是字符串本身的数组。 经过研究,我想到了将其存储为以下接口类型:

  var v interface {} = [{“ name”:“ ravi”},
 [“ art”  ,“编码”,“音乐”,“旅行”],
 {“ language”:“ golang”},
 {“ experience”:“ no”} 
] 
    
 
 

仍然,我遇到了一些无法找到的编译错误。

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dougu5950 2015-10-09 06:52
    已采纳

    What you're asking for is possible -- playground link:

    package main
    
    import "fmt"
    
    func main() {
        v := []interface{}{
            map[string]string{"name": "ravi"},
            []string{"art", "coding", "music", "travel"},
            map[string]string{"language": "golang"},
            map[string]string{"experience": "no"},
        }
        fmt.Println(v)
    }
    

    But you probably don't want to be doing this. You're fighting the type system, I would question why you're using Go if you were doing it like this. Consider leveraging the type system -- playground link:

    package main
    
    import "fmt"
    
    type candidate struct {
        name string
        interests []string
        language string
        experience bool
    }
    
    func main() {
        candidates := []candidate{
            {
                name: "ravi",
                interests: []string{"art", "coding", "music", "travel"},
                language: "golang",
                experience: false,
            },
        }
        fmt.Println(candidates)
    }
    
    点赞 打赏 评论
  • doushen4719 2015-10-09 07:01

    Perfect python syntax, but go unfortunately use something less readable. https://golang.org/ref/spec#Composite_literals

    点赞 打赏 评论

相关推荐 更多相似问题