英文:
Issue Marshaling YAML with an array of struct
问题
我期望生成的yaml文件中包含作为空对象写入的servers数组。我该如何修复这个问题,以便将servers数组写入yaml文件中?
代码:
package configwritter
import (
"fmt"
"io/ioutil"
"log"
"gopkg.in/yaml.v2" //go get gopkg.in/yaml.v2
)
type Server struct {
name string `yaml:"name"`
ip string `yaml:"ip"`
}
type Confugration struct {
Name string
Servers []Server
}
func WriteConfig() {
config := Confugration{
Name: "Test",
Servers: []Server{
{"server1", "10.0.0.100"},
{"server1", "10.0.0.101"},
},
}
data, err := yaml.Marshal(&config)
if err != nil {
log.Fatal(err)
}
err2 := ioutil.WriteFile("config.yaml", data, 0)
if err2 != nil {
log.Fatal(err2)
}
fmt.Println("data written")
}
输出:
name: Test
servers:
- {}
- {}
你需要将Server结构体中的字段名首字母大写,以便在序列化为yaml时能够访问到它们。将name
改为Name
,将ip
改为IP
。修改后的代码如下:
type Server struct {
Name string `yaml:"name"`
IP string `yaml:"ip"`
}
这样修改后,生成的yaml文件将包含正确的服务器信息。
英文:
I am expecting the resulting yaml file to contain the servers array which are being written as empty objects. How could i go about fixing this so that the servers array is written to the yaml file?
Code:
package configwritter
import (
"fmt"
"io/ioutil"
"log"
"gopkg.in/yaml.v2" //go get gopkg.in/yaml.v2
)
type Server struct {
name string `yaml:"name"`
ip string `yaml:"ip"`
}
type Confugration struct {
Name string
Servers []Server
}
func WriteConfig() {
config := Confugration{
Name: "Test",
Servers: []Server{
{"server1", "10.0.0.100"},
{"server1", "10.0.0.101"},
},
}
data, err := yaml.Marshal(&config)
if err != nil {
log.Fatal(err)
}
err2 := ioutil.WriteFile("config.yaml", data, 0)
if err2 != nil {
log.Fatal(err2)
}
fmt.Println("data written")
}
Output:
name: Test
servers:
- {}
- {}
答案1
得分: 2
似乎你的Server
结构体上的字段需要是公开的,这样yaml
模块才能读取它们。
根据Marshal
文档:
> 只有导出的结构体字段(首字母大写)才会被编组。
你可以通过更改Server
的类型定义来解决这个问题,使字段变为导出的(首字母大写),像这样:
type Server struct {
Name string `yaml:"name"`
IP string `yaml:"ip"`
}
生成的config.yaml
文件如下:
name: Test
servers:
- name: server1
ip: 10.0.0.100
- name: server1
ip: 10.0.0.101
英文:
It seems the fields on your Server
struct need to be public in order for the yaml
module to read them.
From the Marshal
documentation:
> Struct fields are only marshalled if they are exported (have an upper case first letter)
You can fix this by changing the type definition for Server
so that the fields are exported (have capitalized names), like so:
type Server struct {
Name string `yaml:"name"`
IP string `yaml:"ip"`
}
With output config.yaml
file:
name: Test
servers:
- name: server1
ip: 10.0.0.100
- name: server1
ip: 10.0.0.101
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论