我有一個簡單的結構,例如:
type Foo struct {
On string `yaml:"on"`
}
并希望以任何一種方式將此結構編組為 YAML 字串
- 方式1:https ://go.dev/play/p/Btwt3Gi09ZG
- 方式2:https ://go.dev/play/p/r9jwscnuOAR
始終在鍵“on”上使用雙引號得到相同的結果
"on": hello
我怎樣才能避免這種情況?以下是我想要的結果
on: hello
go的版本是 go1.17.2 darwin/amd64
uj5u.com熱心網友回復:
這將是無效的 YAML1.1(或至少令人困惑),因為on關鍵字被解釋為布林值true(請參閱YAML1.1 規范)。
根據go-yaml 檔案:
yaml 包支持 YAML 1.2 的大部分內容,但保留了 1.1 中的一些行為以實作向后兼容性。
具體來說,從 yaml 包的 v3 開始:
- 只要將 YAML 1.1 布林值(是/否,開/關)解碼為型別化的布林值,它們就受支持。否則,它們表現為字串。YAML 1.2 中的布林值僅是真/假。
如果您更改yaml:"on"為其他任何內容,例如yaml:"foo"key 將不會被參考。
type T struct {
On string `yaml:"on"`
Foo string `yaml:"foo"`
}
func main() {
t := T{
On: "Hello",
Foo: "world",
}
b, _ := yaml.Marshal(&t)
fmt.Println(string(b))
}
// "on": hello
// foo: world
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/422110.html
標籤:
