Go YAML Marshal

Jmnote (토론 | 기여)님의 2023년 2월 3일 (금) 16:07 판 (→‎예시: Animals)
(차이) ← 이전 판 | 최신판 (차이) | 다음 판 → (차이)

1 개요

Go YAML Marshal()
  • 구조체 → YAML

2 예시: ColorGroup

package main
import (
        "fmt"
        "gopkg.in/yaml.v3"
)

type ColorGroup struct {
	ID     int
	Name   string
	Colors []string
}

func main() {
	colorGroup := ColorGroup{
		ID:     1,
		Name:   "Reds",
		Colors: []string{"Crimson", "Red", "Ruby", "Maroon"},
	}
	yamlBytes, err := yaml.Marshal(colorGroup)
	if err != nil {
		fmt.Println("error:", err)
	}
	fmt.Println(string(yamlBytes))
}

3 예시: Animals

package main
import (
        "fmt"
        "gopkg.in/yaml.v3"
)

type Animal struct {
	Name  string
	Order string
}

func main() {
	animals := []Animal{
		{
			Name: "Platypus",
			Order: "Monotremata",
		},
		{
			Name: "Quoll",
			Order: "Dasyuromorphia",
		},
	}
	yamlBytes, err := yaml.Marshal(animals)
	if err != nil {
		fmt.Println("error:", err)
	}
	fmt.Println(string(yamlBytes))
}

4 같이 보기

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