mirror of
https://github.com/unknwon/the-way-to-go_ZH_CN.git
synced 2025-08-12 02:16:48 +08:00
update book code
This commit is contained in:
41
eBook/examples/chapter_12/gob1.go
Normal file
41
eBook/examples/chapter_12/gob1.go
Normal file
@@ -0,0 +1,41 @@
|
||||
// gob1.go
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"encoding/gob"
|
||||
"log"
|
||||
)
|
||||
|
||||
type P struct {
|
||||
X, Y, Z int
|
||||
Name string
|
||||
}
|
||||
|
||||
type Q struct {
|
||||
X, Y *int32
|
||||
Name string
|
||||
}
|
||||
|
||||
func main() {
|
||||
// Initialize the encoder and decoder. Normally enc and dec would be
|
||||
// bound to network connections and the encoder and decoder would
|
||||
// run in different processes.
|
||||
var network bytes.Buffer // Stand-in for a network connection
|
||||
enc := gob.NewEncoder(&network) // Will write to network.
|
||||
dec := gob.NewDecoder(&network) // Will read from network.
|
||||
// Encode (send) the value.
|
||||
err := enc.Encode(P{3, 4, 5, "Pythagoras"})
|
||||
if err != nil {
|
||||
log.Fatal("encode error:", err)
|
||||
}
|
||||
// Decode (receive) the value.
|
||||
var q Q
|
||||
err = dec.Decode(&q)
|
||||
if err != nil {
|
||||
log.Fatal("decode error:", err)
|
||||
}
|
||||
fmt.Printf("%q: {%d,%d}\n", q.Name, *q.X, *q.Y)
|
||||
}
|
||||
// Output: "Pythagoras": {3,4}
|
Reference in New Issue
Block a user