gpt4 book ai didi

go - 如何读取 YAML 文件

转载 作者:IT老高 更新时间:2023-10-28 13:04:04 26 4
gpt4 key购买 nike

我在读取 YAML 文件时遇到问题。我认为这是文件结构中的一些东西,但我不知道是什么。

YAML 文件:

conf:
hits:5
time:5000000

代码:

type conf struct {
hits int64 `yaml:"hits"`
time int64 `yaml:"time"`
}


func (c *conf) getConf() *conf {

yamlFile, err := ioutil.ReadFile("conf.yaml")
if err != nil {
log.Printf("yamlFile.Get err #%v ", err)
}
err = yaml.Unmarshal(yamlFile, c)
if err != nil {
log.Fatalf("Unmarshal: %v", err)
}

return c
}

最佳答案

你的 yaml 文件必须是

hits: 5
time: 5000000

您的代码应如下所示:

package main

import (
"fmt"
"gopkg.in/yaml.v2"
"io/ioutil"
"log"
)

type conf struct {
Hits int64 `yaml:"hits"`
Time int64 `yaml:"time"`
}

func (c *conf) getConf() *conf {

yamlFile, err := ioutil.ReadFile("conf.yaml")
if err != nil {
log.Printf("yamlFile.Get err #%v ", err)
}
err = yaml.Unmarshal(yamlFile, c)
if err != nil {
log.Fatalf("Unmarshal: %v", err)
}

return c
}

func main() {
var c conf
c.getConf()

fmt.Println(c)
}

主要错误是结构的大写字母。

关于go - 如何读取 YAML 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30947534/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com