Go omitempty

1 개요[ | ]

Go omitempty
package main

import (
	"encoding/json"
	"fmt"
)

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

func main() {
	a := Fruit{Name: "apple", Price: 42}
	b := Fruit{Name: "banana"}
	c := Fruit{Price: 123}
	m := Fruit{Name: "melon", Price: 0}

	aBytes, _ := json.Marshal(a)
	bBytes, _ := json.Marshal(b)
	cBytes, _ := json.Marshal(c)
	mBytes, _ := json.Marshal(m)

	fmt.Println(string(aBytes)) // {"name":"apple","price":42}
	fmt.Println(string(bBytes)) // {"name":"banana"}
	fmt.Println(string(cBytes)) // {"price":123}
	fmt.Println(string(mBytes)) // {"name":"melon"}
}

2 같이 보기[ | ]

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