"Go YAML omitempty"의 두 판 사이의 차이

(새 문서: ==개요== ;Go YAML omitempty ==Marshal== <syntaxhighlight lang='go' run> package main import ( "fmt" "gopkg.in/yaml.v3" ) type Fruit struct { Name string `yaml:"name"` Pric...)
 
2번째 줄: 2번째 줄:
;Go YAML omitempty
;Go YAML omitempty


==Unmarshal==
<syntaxhighlight lang='go' run>
package main
import (
"fmt"
"gopkg.in/yaml.v3"
)
var data = []byte(`
- name: "apple"
  price: 1
- name: "banana"
- name: "melon"
`)
type Fruit struct {
Name  string `yaml:"name"`
Price int    `yaml:"price,omitempty"`
}
func main() {
var fruits []Fruit
_ = yaml.Unmarshal(data, &fruits)
fmt.Printf("%+v", fruits)
}
</syntaxhighlight>


==Marshal==
==Marshal==

2023년 4월 5일 (수) 04:47 판

1 개요

Go YAML omitempty

2 Unmarshal

package main

import (
	"fmt"

	"gopkg.in/yaml.v3"
)

var data = []byte(`
- name: "apple"
  price: 1
- name: "banana"
- name: "melon"
`)

type Fruit struct {
	Name  string `yaml:"name"`
	Price int    `yaml:"price,omitempty"`
}

func main() {
	var fruits []Fruit
	_ = yaml.Unmarshal(data, &fruits)
	fmt.Printf("%+v", fruits)
}

3 Marshal

package main

import (
	"fmt"

	"gopkg.in/yaml.v3"
)

type Fruit struct {
	Name  string `yaml:"name"`
	Price int    `yaml:"price,omitempty"`
}

func main() {
	fruits := []Fruit{
		{Name: "apple", Price: 1},
		{Name: "banana", Price: 0},
		{Name: "melon", Price: 0},
	}
	yamlBytes, _ := yaml.Marshal(fruits)
	fmt.Println(string(yamlBytes))
}

4 같이 보기

문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}