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.

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

报告相同问题?

悬赏问题

  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗