英文:
Creating advanced structure with neast and arrays in golang
问题
大家好,我正在尝试学习Go语言,我正在创建一个需要创建和初始化结构的项目,但我在写和初始化结构时遇到了困难。如果有人能帮助我,我将非常感激。
以下是要翻译的内容:
大家好,我正在尝试学习Go语言,我正在创建一个需要创建和初始化结构的项目,但我在写和初始化结构时遇到了困难。如果有人能帮助我,我将非常感激。
{
"name": "message",
"args": [
{
"method": "joinChannel",
"params": {
"channel": "CHANNEL",
"name": "USERNAME",
"token": "XXXX",
"isAdmin": false
}
}
]
}
我在谷歌上寻找了一些示例,但只找到了一些简单的例子。这是我想到的解决方案:
type Channel struct {
Name string json:"name"
Args []struct {
Method string json:"method"
Params struct {
Channel string json:"channel"
Name string json:"name"
Token string json:"token"
Isadmin bool json:"isAdmin"
} json:"params"
} json:"args"
}
有没有更简洁的方法来实现这个?
英文:
Hi guys I am trying to learn golang I am creating my own project which requires to create structure that I have hard times to write and initalized. I would be greatful if anyone can help me out with it.
{
"name":"message",
"args":[
{
"method":"joinChannel",
"params":{
"channel":"CHANNEL",
"name":"USERNAME",
"token":"XXXX",
"isAdmin":false
}
}
]
}
I was looking for some examples on google but only thing I could find was easie ones. This is what I came up
type Channel struct {
Name string `json:"name"`
Args []struct {
Method string `json:"method"`
Params struct {
Channel string `json:"channel"`
Name string `json:"name"`
Token string `json:"token"`
Isadmin bool `json:"isAdmin"`
} `json:"params"`
} `json:"args"`
}
Is there more transparent way to do it?
答案1
得分: 1
如果你想将类型分开而不是内联声明,代码会像这样:
type Channel struct {
Name string `json:"name"`
Args []Arg `json:"args"`
}
type Arg struct {
Method string `json:"method"`
Params Params `json:"params"`
}
type Params struct {
Channel string `json:"channel"`
Name string `json:"name"`
Token string `json:"token"`
Isadmin bool `json:"isAdmin"`
}
myChan := Channel{
Name: "Name",
Args: []Arg{
Arg{
Method: "Method",
Params: Params{
Channel: "Channel",
Name: "Name",
Token: "Token",
Isadmin: true,
},
},
},
}
以上是你要翻译的内容。
英文:
If you wanted to break the types out rather than having those anonymous declarations inline it would look like this;
type Channel struct {
Name string `json:"name"`
Args []Arg `json:"args"`
}
type Arg struct {
Method string `json:"method"`
Params Params `json:"params"`
}
type Params struct {
Channel string `json:"channel"`
Name string `json:"name"`
Token string `json:"token"`
Isadmin bool `json:"isAdmin"`
}
myChan := Channel{"Name", []Arg{ Arg{"Method", Params{ "Channel", "Name", "Token", true } } } }
答案2
得分: 0
你可以像这样分离嵌套的结构体。
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论