Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/mercurial/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/image/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在golang中读取yaml配置文件时,我是否总是需要结构?_Go - Fatal编程技术网

在golang中读取yaml配置文件时,我是否总是需要结构?

在golang中读取yaml配置文件时,我是否总是需要结构?,go,Go,我想从Golang中的yaml读取配置常量 例如: 我有config.yml server: host: "localhost" port: 8080 和一个配置结构 type Config struct { Server struct { Port string `yaml:"port"` Host string `yaml:"host"` } `yaml:"server"` } 然后我可以这样读: f, err := os.Open

我想从Golang中的yaml读取配置常量

例如: 我有config.yml

server:
  host: "localhost"
  port: 8080
和一个配置结构

type Config struct {
    Server struct {
        Port string `yaml:"port"`
        Host string `yaml:"host"`
    } `yaml:"server"`
}
然后我可以这样读:

f, err := os.Open("config.yml")
if err != nil {
    processError(err)
}

var cfg Config
decoder := yaml.NewDecoder(f)
err = decoder.Decode(&cfg)
if err != nil {
    processError(err)
}
我正在使用gopkg.in/yaml.v2

我想解析它,然后读取常量,我需要配置一个结构吗 结构


提前感谢

您可以将yaml文件解组到接口{}:

var data interface{}
yaml.Unmarshal(input,&data)
需要注意的一点是,库将解组映射到[interface{}]interface{},而不是映射[string]interface{}