英文:
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
}
答案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), ¶ms)
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]))
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论