尝试将 yaml 数据转换为结构时为空输出 [英] Empty output while trying to convert a yaml data into a struct

查看:33
本文介绍了尝试将 yaml 数据转换为结构时为空输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将 yaml 数据转换为结构并打印它.我为这个程序得到的输出是空的.

Im trying to convert a yaml data into a struct and print it. The output I get for this program is empty.

package main

import (
"fmt"

"gopkg.in/yaml.v2"
)

type example struct {
    variable1 string
    variable2 string
}

func main() {
    var a example
    yaml.Unmarshal([]byte("variable1: asd
variable2: sdcs"), &a)
    fmt.Println(a.variable1)
}

推荐答案

文档 for Unmarshal 声明

结构字段只有在被导出(首字母大写)并且使用小写的字段名称作为默认键进行解组时才会解组.

Struct fields are only unmarshalled if they are exported (have an upper case first letter) and are unmarshalled using the field name lowercased as the default key.

因此,将结构元素大写是正确的做法.

So capitalizing your struct elements is the right thing to do.

type example struct {
    Variable1 string
    Variable2 string
}

这篇关于尝试将 yaml 数据转换为结构时为空输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆