doufen3838 2015-07-16 19:14
浏览 139
已采纳

Go中切片内的对象

I am trying to embed multiple objects inside a slice, so I can later export them as JSON. The JSON should look something like this:

[
   {
       name: "Nginx"
       version: "1.9"
   },
   {
       name: ircd-hybrid"
       version: "8.2"
    }
]

So far I have this struct in Go:

type response struct {
    application []struct {
        name        string
        version     string
    }
}

Now (I'm not even sure if the struct is correct), I'm trying to access it this way (again, not sure if this is correct):

   var d response
   d[0].name = "Nginx"
   d[0].version = "1.9"

And so on and so forth. However, it is not working, so I assume I went wrong somewhere. I just don't know where.

  • 写回答

1条回答 默认 最新

  • dongsonghen9931 2015-07-16 19:22
    关注

    The form of your 'model' (the struct in Go in this case) isn't quite right. You really just want this;

    type application struct {
            Name        string `json:"name"`   // gotta uppercase these so they're exported 
            Version     string `json:"version"` // otherwise you can't marshal them
        }
    apps := []application{
         application{Name:"Windows", Version:"10"}
    }
    app := application{Name:"Linux", Vesion:"14.2"}
    apps = append(apps, app)
    

    The json opens with [ meaning it is just an array, there is no enclosing object. If there were you would want another type with an application array ( []application ) property. To add items to that array you can use append or initialize it with some instance using the 'composite literal' syntax.

    EDIT: I added some annotations so the json produced will have lower cased names like in your example. If a property isn't exported in Go other libraries like encoding/json won't be able to use it.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染