0

go-yaml 的默认 map 类型是 map[any]any

 1 year ago
source link: https://diabloneo.github.io//2022/11/02/go-yaml-default-map-type-is-map-any-any/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

go-yaml 的默认 map 类型是 map[any]any

Nov 2, 2022

Go 语言的 yaml 库 <github.com/go-yaml/yaml> 的默认 map 类型是 map[any]any,而不是 map[string]any

V2 代码:https://github.com/go-yaml/yaml/blob/v2/decode.go#L241 V3 代码:https://github.com/go-yaml/yaml/blob/v3/decode.go#L334

因此,当使用这个库对 yaml 内容进行 unmarshal 的时候,由 go-yaml 自动创建的 map 的类型是 map[any]any

package main

import (
	"fmt"
	"log"

	"gopkg.in/yaml.v2"
)

var content = `
storage:
  settings:
    fs:
      ad:
        username: admin
      ldap:
        password: password

`

type Storage struct {
	Settings map[string]any `yaml:"settings"`
}

type Config struct {
	Storage *Storage `yaml:"storage"`
}

func main() {
	c := new(Config)
	err := yaml.Unmarshal([]byte(content), c)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("%T\n", c.Storage.Settings["fs"])
}

上面代码的输出是:

❯ go run testcmd.go
map[interface {}]interface {}

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK