如何正确解析 YAML 文件中的 rune 参数

huangapple go评论93阅读模式
英文:

How to correctly parse rune parameter in YAML file

问题

我尝试在Yaml中像这样传递rune参数:

CsvDelimiter: '';''

然后我将Yaml解析为结构体:

type Params struct {
  ...
  CsvDelimiter rune `yaml: "CsvDelimiter"`
  ...
}

但是Params.CsvDelimiter是空的。

如何正确地从Yaml中传递rune参数?

英文:

I tried to pass rune parameter in Yaml like this:

CsvDelimiter: ';'

then i parse yaml to struct

type Params struct {
  ...
  CsvDelimiter rune `yaml: "CsvDelimiter"`
  ...
}

but then Params.CsvDelimiter is empty

how correctly pass rune parameters from Yaml?

答案1

得分: 2

假设您正在使用gopkg.in/yaml.v3包,您可以声明一个自定义的rune类型,并让它实现Unmarshaler接口。

type Rune rune

func (r *Rune) UnmarshalYAML(n *yaml.Node) error {
    var s string
    if err := n.Decode(&s); err != nil {
        return err
    }
    
    rn, _ := utf8.DecodeRune([]byte(s))
    *r = Rune(rn)
    return nil
}

https://play.golang.org/p/UDYU_EAJNqn

英文:

Assuming you're using the gopkg.in/yaml.v3 package, you could declare a custom rune type and have it implement the Unmarshaler interface.

type Rune rune

func (r *Rune) UnmarshalYAML(n *yaml.Node) error {
	var s string
	if err := n.Decode(&s); err != nil {
		return err
	}
	
	rn, _ := utf8.DecodeRune([]byte(s))
	*r = Rune(rn)
	return nil
}

https://play.golang.org/p/UDYU_EAJNqn

答案2

得分: 0

YAML解组器不知道如何处理rune,但是你可以像这样从字符串中提取rune。

package main

import (
	"fmt"
	"gopkg.in/yaml.v2"
)

type Params struct {
	CsvDelimiter string `yaml:"CsvDelimiter"`
}

func main() {
	str := `CsvDelimiter: ';'
`
	params := Params{}
	err := yaml.Unmarshal([]byte(str), &params)
	if err != nil {
		panic(err)
	}
	fmt.Println(rune(params.CsvDelimiter[0]))
}
英文:

The YAML unmarshaler does not know how to handle a rune, but you can extract a rune from the string like this.

package main

import (
	"fmt"
	"gopkg.in/yaml.v2"
)

type Params struct {
	CsvDelimiter string `yaml:"CsvDelimiter"`
}

func main() {
	str := `CsvDelimiter: ';'`
	params := Params{}
	err := yaml.Unmarshal([]byte(str), &params)
	if err != nil {
		panic(err)
	}
	fmt.Println(rune(params.CsvDelimiter[0]))
}

huangapple
  • 本文由 发表于 2021年7月6日 01:35:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/68260117.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定