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

53 lines
1.4 KiB
Go
Raw Normal View History

2019-09-07 22:23:42 +03:00
// Copyright © 2018 Inanc Gumus
// Learn Go Programming Course
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
//
2019-10-30 19:34:44 +03:00
// For more tutorials : https://learngoprogramming.com
// In-person training : https://www.linkedin.com/in/inancgumus/
// Follow me on twitter: https://twitter.com/inancgumus
2019-09-07 22:23:42 +03:00
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 {
2019-11-02 13:37:41 +03:00
log.Fatal(err)
2019-10-21 15:21:34 +03:00
}
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 {
2019-11-02 13:37:41 +03:00
log.Fatal(err)
2019-10-21 15:21:34 +03:00
}
// 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.
2019-11-02 13:37:41 +03:00
- log.Fatal() can print the given error message and terminate the program.
2019-10-21 15:21:34 +03:00
- Use it only from the main(). Do not use it in other functions.
- main() is should be the main driver of a program.
*/