Files
learngo/interfaces/12-marshaler/main.go

52 lines
1.3 KiB
Go
Raw Normal View History

2019-09-07 22:23:42 +03:00
// For more tutorials: https://blog.learngoprogramming.com
//
// Copyright © 2018 Inanc Gumus
// Learn Go Programming Course
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
//
package main
import (
"fmt"
2019-10-21 15:21:34 +03:00
"log"
2019-09-07 22:23:42 +03:00
)
2019-10-17 14:11:51 +03:00
func main() {
2019-10-21 15:21:34 +03:00
// First encode products as JSON:
data, err := encode()
if err != nil {
log.Fatalln(err)
}
fmt.Println(string(data))
2019-09-07 22:23:42 +03:00
2019-10-21 15:21:34 +03:00
// Then decode them back from JSON:
l, err := decode(data)
if err != nil {
log.Fatalln(err)
}
// Let the list value print itself:
2019-10-17 14:11:51 +03:00
fmt.Print(l)
2019-09-07 22:23:42 +03:00
}
2019-10-21 15:21:34 +03:00
/*
Summary:
- json.Marshal() and json.MarshalIndent() can only encode primitive types.
2019-10-23 21:00:05 +03:00
- Custom types can tell the encoder how to encode.
- To do that satisfy the json.Marshaler interface.
2019-10-21 15:21:34 +03:00
- json.Unmarshal() can only decode primitive types.
2019-10-23 21:00:05 +03:00
- Custom types can tell the decoder how to decode.
- To do that satisfy the json.Unmarshaler interface.
2019-10-21 15:21:34 +03:00
- strconv.AppendInt() can append an int value to a []byte.
- There are several other functions in the strconv package for other primitive types as well.
- Do not make unnecessary string <-> []byte conversions.
- log.Fatalln() can print the given error message and terminate the program.
- Use it only from the main(). Do not use it in other functions.
- main() is should be the main driver of a program.
*/