summaryrefslogtreecommitdiff
path: root/devdocs/go/encoding%2Fgob%2Findex.html
blob: 867a1b6c3c3bc1b456a316d5c5d9c4165d6b5d47 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
<h1> Package gob  </h1>     <ul id="short-nav">
<li><code>import "encoding/gob"</code></li>
<li><a href="#pkg-overview" class="overviewLink">Overview</a></li>
<li><a href="#pkg-index" class="indexLink">Index</a></li>
<li><a href="#pkg-examples" class="examplesLink">Examples</a></li>
</ul>     <h2 id="pkg-overview">Overview </h2> <p>Package gob manages streams of gobs - binary values exchanged between an <a href="#Encoder">Encoder</a> (transmitter) and a <a href="#Decoder">Decoder</a> (receiver). A typical use is transporting arguments and results of remote procedure calls (RPCs) such as those provided by <span>net/rpc</span>. </p>
<p>The implementation compiles a custom codec for each data type in the stream and is most efficient when a single <a href="#Encoder">Encoder</a> is used to transmit a stream of values, amortizing the cost of compilation. </p>
<h3 id="hdr-Basics">Basics</h3> <p>A stream of gobs is self-describing. Each data item in the stream is preceded by a specification of its type, expressed in terms of a small set of predefined types. Pointers are not transmitted, but the things they point to are transmitted; that is, the values are flattened. Nil pointers are not permitted, as they have no value. Recursive types work fine, but recursive values (data with cycles) are problematic. This may change. </p>
<p>To use gobs, create an <a href="#Encoder">Encoder</a> and present it with a series of data items as values or addresses that can be dereferenced to values. The <a href="#Encoder">Encoder</a> makes sure all type information is sent before it is needed. At the receive side, a <a href="#Decoder">Decoder</a> retrieves values from the encoded stream and unpacks them into local variables. </p>
<h3 id="hdr-Types_and_Values">Types and Values</h3> <p>The source and destination values/types need not correspond exactly. For structs, fields (identified by name) that are in the source but absent from the receiving variable will be ignored. Fields that are in the receiving variable but missing from the transmitted type or value will be ignored in the destination. If a field with the same name is present in both, their types must be compatible. Both the receiver and transmitter will do all necessary indirection and dereferencing to convert between gobs and actual Go values. For instance, a gob type that is schematically, </p>
<pre data-language="go">struct { A, B int }
</pre> <p>can be sent from or received into any of these Go types: </p>
<pre data-language="go">struct { A, B int }	// the same
*struct { A, B int }	// extra indirection of the struct
struct { *A, **B int }	// extra indirection of the fields
struct { A, B int64 }	// different concrete value type; see below
</pre> <p>It may also be received into any of these: </p>
<pre data-language="go">struct { A, B int }	// the same
struct { B, A int }	// ordering doesn't matter; matching is by name
struct { A, B, C int }	// extra field (C) ignored
struct { B int }	// missing field (A) ignored; data will be dropped
struct { B, C int }	// missing field (A) ignored; extra field (C) ignored.
</pre> <p>Attempting to receive into these types will draw a decode error: </p>
<pre data-language="go">struct { A int; B uint }	// change of signedness for B
struct { A int; B float }	// change of type for B
struct { }			// no field names in common
struct { C, D int }		// no field names in common
</pre> <p>Integers are transmitted two ways: arbitrary precision signed integers or arbitrary precision unsigned integers. There is no int8, int16 etc. discrimination in the gob format; there are only signed and unsigned integers. As described below, the transmitter sends the value in a variable-length encoding; the receiver accepts the value and stores it in the destination variable. Floating-point numbers are always sent using IEEE-754 64-bit precision (see below). </p>
<p>Signed integers may be received into any signed integer variable: int, int16, etc.; unsigned integers may be received into any unsigned integer variable; and floating point values may be received into any floating point variable. However, the destination variable must be able to represent the value or the decode operation will fail. </p>
<p>Structs, arrays and slices are also supported. Structs encode and decode only exported fields. Strings and arrays of bytes are supported with a special, efficient representation (see below). When a slice is decoded, if the existing slice has capacity the slice will be extended in place; if not, a new array is allocated. Regardless, the length of the resulting slice reports the number of elements decoded. </p>
<p>In general, if allocation is required, the decoder will allocate memory. If not, it will update the destination variables with values read from the stream. It does not initialize them first, so if the destination is a compound value such as a map, struct, or slice, the decoded values will be merged elementwise into the existing variables. </p>
<p>Functions and channels will not be sent in a gob. Attempting to encode such a value at the top level will fail. A struct field of chan or func type is treated exactly like an unexported field and is ignored. </p>
<p>Gob can encode a value of any type implementing the <a href="#GobEncoder">GobEncoder</a> or <span>encoding.BinaryMarshaler</span> interfaces by calling the corresponding method, in that order of preference. </p>
<p>Gob can decode a value of any type implementing the <a href="#GobDecoder">GobDecoder</a> or <span>encoding.BinaryUnmarshaler</span> interfaces by calling the corresponding method, again in that order of preference. </p>
<h3 id="hdr-Encoding_Details">Encoding Details</h3> <p>This section documents the encoding, details that are not important for most users. Details are presented bottom-up. </p>
<p>An unsigned integer is sent one of two ways. If it is less than 128, it is sent as a byte with that value. Otherwise it is sent as a minimal-length big-endian (high byte first) byte stream holding the value, preceded by one byte holding the byte count, negated. Thus 0 is transmitted as (00), 7 is transmitted as (07) and 256 is transmitted as (FE 01 00). </p>
<p>A boolean is encoded within an unsigned integer: 0 for false, 1 for true. </p>
<p>A signed integer, i, is encoded within an unsigned integer, u. Within u, bits 1 upward contain the value; bit 0 says whether they should be complemented upon receipt. The encode algorithm looks like this: </p>
<pre data-language="go">var u uint
if i &lt; 0 {
	u = (^uint(i) &lt;&lt; 1) | 1 // complement i, bit 0 is 1
} else {
	u = (uint(i) &lt;&lt; 1) // do not complement i, bit 0 is 0
}
encodeUnsigned(u)
</pre> <p>The low bit is therefore analogous to a sign bit, but making it the complement bit instead guarantees that the largest negative integer is not a special case. For example, -129=^128=(^256&gt;&gt;1) encodes as (FE 01 01). </p>
<p>Floating-point numbers are always sent as a representation of a float64 value. That value is converted to a uint64 using <span>math.Float64bits</span>. The uint64 is then byte-reversed and sent as a regular unsigned integer. The byte-reversal means the exponent and high-precision part of the mantissa go first. Since the low bits are often zero, this can save encoding bytes. For instance, 17.0 is encoded in only three bytes (FE 31 40). </p>
<p>Strings and slices of bytes are sent as an unsigned count followed by that many uninterpreted bytes of the value. </p>
<p>All other slices and arrays are sent as an unsigned count followed by that many elements using the standard gob encoding for their type, recursively. </p>
<p>Maps are sent as an unsigned count followed by that many key, element pairs. Empty but non-nil maps are sent, so if the receiver has not allocated one already, one will always be allocated on receipt unless the transmitted map is nil and not at the top level. </p>
<p>In slices and arrays, as well as maps, all elements, even zero-valued elements, are transmitted, even if all the elements are zero. </p>
<p>Structs are sent as a sequence of (field number, field value) pairs. The field value is sent using the standard gob encoding for its type, recursively. If a field has the zero value for its type (except for arrays; see above), it is omitted from the transmission. The field number is defined by the type of the encoded struct: the first field of the encoded type is field 0, the second is field 1, etc. When encoding a value, the field numbers are delta encoded for efficiency and the fields are always sent in order of increasing field number; the deltas are therefore unsigned. The initialization for the delta encoding sets the field number to -1, so an unsigned integer field 0 with value 7 is transmitted as unsigned delta = 1, unsigned value = 7 or (01 07). Finally, after all the fields have been sent a terminating mark denotes the end of the struct. That mark is a delta=0 value, which has representation (00). </p>
<p>Interface types are not checked for compatibility; all interface types are treated, for transmission, as members of a single "interface" type, analogous to int or []byte - in effect they're all treated as interface{}. Interface values are transmitted as a string identifying the concrete type being sent (a name that must be pre-defined by calling <a href="#Register">Register</a>), followed by a byte count of the length of the following data (so the value can be skipped if it cannot be stored), followed by the usual encoding of concrete (dynamic) value stored in the interface value. (A nil interface value is identified by the empty string and transmits no value.) Upon receipt, the decoder verifies that the unpacked concrete item satisfies the interface of the receiving variable. </p>
<p>If a value is passed to <a href="#Encoder.Encode">Encoder.Encode</a> and the type is not a struct (or pointer to struct, etc.), for simplicity of processing it is represented as a struct of one field. The only visible effect of this is to encode a zero byte after the value, just as after the last field of an encoded struct, so that the decode algorithm knows when the top-level value is complete. </p>
<p>The representation of types is described below. When a type is defined on a given connection between an <a href="#Encoder">Encoder</a> and <a href="#Decoder">Decoder</a>, it is assigned a signed integer type id. When <a href="#Encoder.Encode">Encoder.Encode</a>(v) is called, it makes sure there is an id assigned for the type of v and all its elements and then it sends the pair (typeid, encoded-v) where typeid is the type id of the encoded type of v and encoded-v is the gob encoding of the value v. </p>
<p>To define a type, the encoder chooses an unused, positive type id and sends the pair (-type id, encoded-type) where encoded-type is the gob encoding of a wireType description, constructed from these types: </p>
<pre data-language="go">type wireType struct {
	ArrayT           *ArrayType
	SliceT           *SliceType
	StructT          *StructType
	MapT             *MapType
	GobEncoderT      *gobEncoderType
	BinaryMarshalerT *gobEncoderType
	TextMarshalerT   *gobEncoderType

}
type arrayType struct {
	CommonType
	Elem typeId
	Len  int
}
type CommonType struct {
	Name string // the name of the struct type
	Id  int    // the id of the type, repeated so it's inside the type
}
type sliceType struct {
	CommonType
	Elem typeId
}
type structType struct {
	CommonType
	Field []*fieldType // the fields of the struct.
}
type fieldType struct {
	Name string // the name of the field.
	Id   int    // the type id of the field, which must be already defined
}
type mapType struct {
	CommonType
	Key  typeId
	Elem typeId
}
type gobEncoderType struct {
	CommonType
}
</pre> <p>If there are nested type ids, the types for all inner type ids must be defined before the top-level type id is used to describe an encoded-v. </p>
<p>For simplicity in setup, the connection is defined to understand these types a priori, as well as the basic gob types int, uint, etc. Their ids are: </p>
<pre data-language="go">bool        1
int         2
uint        3
float       4
[]byte      5
string      6
complex     7
interface   8
// gap for reserved ids.
WireType    16
ArrayType   17
CommonType  18
SliceType   19
StructType  20
FieldType   21
// 22 is slice of fieldType.
MapType     23
</pre> <p>Finally, each message created by a call to Encode is preceded by an encoded unsigned integer count of the number of bytes remaining in the message. After the initial type name, interface values are wrapped the same way; in effect, the interface value acts like a recursive invocation of Encode. </p>
<p>In summary, a gob stream looks like </p>
<pre data-language="go">(byteCount (-type id, encoding of a wireType)* (type id, encoding of a value))*
</pre> <p>where * signifies zero or more repetitions and the type id of a value must be predefined or be defined before the value in the stream. </p>
<p>Compatibility: Any future changes to the package will endeavor to maintain compatibility with streams encoded using previous versions. That is, any released version of this package should be able to decode data written with any previously released version, subject to issues such as security fixes. See the Go compatibility document for background: <a href="https://golang.org/doc/go1compat">https://golang.org/doc/go1compat</a> </p>
<p>See "Gobs of data" for a design discussion of the gob wire format: <a href="https://blog.golang.org/gobs-of-data">https://blog.golang.org/gobs-of-data</a> </p>
<h3 id="hdr-Security">Security</h3> <p>This package is not designed to be hardened against adversarial inputs, and is outside the scope of <a href="https://go.dev/security/policy">https://go.dev/security/policy</a>. In particular, the <a href="#Decoder">Decoder</a> does only basic sanity checking on decoded input sizes, and its limits are not configurable. Care should be taken when decoding gob data from untrusted sources, which may consume significant resources. </p>   <h4 id="example__basic"> <span class="text">Example (Basic)</span>
</h4> <p>This example shows the basic usage of the package: Create an encoder, transmit some values, receive them with a decoder. </p> <p>Code:</p> <pre class="code" data-language="go">package gob_test

import (
    "bytes"
    "encoding/gob"
    "fmt"
    "log"
)

type P struct {
    X, Y, Z int
    Name    string
}

type Q struct {
    X, Y *int32
    Name string
}

// This example shows the basic usage of the package: Create an encoder,
// transmit some values, receive them with a decoder.
func Example_basic() {
    // 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(&amp;network) // Will write to network.
    dec := gob.NewDecoder(&amp;network) // Will read from network.

    // Encode (send) some values.
    err := enc.Encode(P{3, 4, 5, "Pythagoras"})
    if err != nil {
        log.Fatal("encode error:", err)
    }
    err = enc.Encode(P{1782, 1841, 1922, "Treehouse"})
    if err != nil {
        log.Fatal("encode error:", err)
    }

    // Decode (receive) and print the values.
    var q Q
    err = dec.Decode(&amp;q)
    if err != nil {
        log.Fatal("decode error 1:", err)
    }
    fmt.Printf("%q: {%d, %d}\n", q.Name, *q.X, *q.Y)
    err = dec.Decode(&amp;q)
    if err != nil {
        log.Fatal("decode error 2:", err)
    }
    fmt.Printf("%q: {%d, %d}\n", q.Name, *q.X, *q.Y)

    // Output:
    // "Pythagoras": {3, 4}
    // "Treehouse": {1782, 1841}
}
</pre>      <h4 id="example__encodeDecode"> <span class="text">Example (EncodeDecode)</span>
</h4> <p>This example transmits a value that implements the custom encoding and decoding methods. </p> <p>Code:</p> <pre class="code" data-language="go">package gob_test

import (
    "bytes"
    "encoding/gob"
    "fmt"
    "log"
)

// The Vector type has unexported fields, which the package cannot access.
// We therefore write a BinaryMarshal/BinaryUnmarshal method pair to allow us
// to send and receive the type with the gob package. These interfaces are
// defined in the "encoding" package.
// We could equivalently use the locally defined GobEncode/GobDecoder
// interfaces.
type Vector struct {
    x, y, z int
}

func (v Vector) MarshalBinary() ([]byte, error) {
    // A simple encoding: plain text.
    var b bytes.Buffer
    fmt.Fprintln(&amp;b, v.x, v.y, v.z)
    return b.Bytes(), nil
}

// UnmarshalBinary modifies the receiver so it must take a pointer receiver.
func (v *Vector) UnmarshalBinary(data []byte) error {
    // A simple encoding: plain text.
    b := bytes.NewBuffer(data)
    _, err := fmt.Fscanln(b, &amp;v.x, &amp;v.y, &amp;v.z)
    return err
}

// This example transmits a value that implements the custom encoding and decoding methods.
func Example_encodeDecode() {
    var network bytes.Buffer // Stand-in for the network.

    // Create an encoder and send a value.
    enc := gob.NewEncoder(&amp;network)
    err := enc.Encode(Vector{3, 4, 5})
    if err != nil {
        log.Fatal("encode:", err)
    }

    // Create a decoder and receive a value.
    dec := gob.NewDecoder(&amp;network)
    var v Vector
    err = dec.Decode(&amp;v)
    if err != nil {
        log.Fatal("decode:", err)
    }
    fmt.Println(v)

    // Output:
    // {3 4 5}
}
</pre>      <h4 id="example__interface"> <span class="text">Example (Interface)</span>
</h4> <p>This example shows how to encode an interface value. The key distinction from regular types is to register the concrete type that implements the interface. </p> <p>Code:</p> <pre class="code" data-language="go">package gob_test

import (
    "bytes"
    "encoding/gob"
    "fmt"
    "log"
    "math"
)

type Point struct {
    X, Y int
}

func (p Point) Hypotenuse() float64 {
    return math.Hypot(float64(p.X), float64(p.Y))
}

type Pythagoras interface {
    Hypotenuse() float64
}

// This example shows how to encode an interface value. The key
// distinction from regular types is to register the concrete type that
// implements the interface.
func Example_interface() {
    var network bytes.Buffer // Stand-in for the network.

    // We must register the concrete type for the encoder and decoder (which would
    // normally be on a separate machine from the encoder). On each end, this tells the
    // engine which concrete type is being sent that implements the interface.
    gob.Register(Point{})

    // Create an encoder and send some values.
    enc := gob.NewEncoder(&amp;network)
    for i := 1; i &lt;= 3; i++ {
        interfaceEncode(enc, Point{3 * i, 4 * i})
    }

    // Create a decoder and receive some values.
    dec := gob.NewDecoder(&amp;network)
    for i := 1; i &lt;= 3; i++ {
        result := interfaceDecode(dec)
        fmt.Println(result.Hypotenuse())
    }

    // Output:
    // 5
    // 10
    // 15
}

// interfaceEncode encodes the interface value into the encoder.
func interfaceEncode(enc *gob.Encoder, p Pythagoras) {
    // The encode will fail unless the concrete type has been
    // registered. We registered it in the calling function.

    // Pass pointer to interface so Encode sees (and hence sends) a value of
    // interface type. If we passed p directly it would see the concrete type instead.
    // See the blog post, "The Laws of Reflection" for background.
    err := enc.Encode(&amp;p)
    if err != nil {
        log.Fatal("encode:", err)
    }
}

// interfaceDecode decodes the next interface value from the stream and returns it.
func interfaceDecode(dec *gob.Decoder) Pythagoras {
    // The decode will fail unless the concrete type on the wire has been
    // registered. We registered it in the calling function.
    var p Pythagoras
    err := dec.Decode(&amp;p)
    if err != nil {
        log.Fatal("decode:", err)
    }
    return p
}
</pre>        <h2 id="pkg-index">Index </h2>  <ul id="manual-nav">
<li><a href="#Register">func Register(value any)</a></li>
<li><a href="#RegisterName">func RegisterName(name string, value any)</a></li>
<li><a href="#CommonType">type CommonType</a></li>
<li><a href="#Decoder">type Decoder</a></li>
<li> <a href="#NewDecoder">func NewDecoder(r io.Reader) *Decoder</a>
</li>
<li> <a href="#Decoder.Decode">func (dec *Decoder) Decode(e any) error</a>
</li>
<li> <a href="#Decoder.DecodeValue">func (dec *Decoder) DecodeValue(v reflect.Value) error</a>
</li>
<li><a href="#Encoder">type Encoder</a></li>
<li> <a href="#NewEncoder">func NewEncoder(w io.Writer) *Encoder</a>
</li>
<li> <a href="#Encoder.Encode">func (enc *Encoder) Encode(e any) error</a>
</li>
<li> <a href="#Encoder.EncodeValue">func (enc *Encoder) EncodeValue(value reflect.Value) error</a>
</li>
<li><a href="#GobDecoder">type GobDecoder</a></li>
<li><a href="#GobEncoder">type GobEncoder</a></li>
</ul> <div id="pkg-examples"> <h3>Examples</h3>  <dl> <dd><a class="exampleLink" href="#example__basic">Package (Basic)</a></dd> <dd><a class="exampleLink" href="#example__encodeDecode">Package (EncodeDecode)</a></dd> <dd><a class="exampleLink" href="#example__interface">Package (Interface)</a></dd> </dl> </div> <h3>Package files</h3> <p>  <span>dec_helpers.go</span> <span>decode.go</span> <span>decoder.go</span> <span>doc.go</span> <span>enc_helpers.go</span> <span>encode.go</span> <span>encoder.go</span> <span>error.go</span> <span>type.go</span>  </p>   <h2 id="Register">func <span>Register</span>  </h2> <pre data-language="go">func Register(value any)</pre> <p>Register records a type, identified by a value for that type, under its internal type name. That name will identify the concrete type of a value sent or received as an interface variable. Only types that will be transferred as implementations of interface values need to be registered. Expecting to be used only during initialization, it panics if the mapping between types and names is not a bijection. </p>
<h2 id="RegisterName">func <span>RegisterName</span>  </h2> <pre data-language="go">func RegisterName(name string, value any)</pre> <p>RegisterName is like <a href="#Register">Register</a> but uses the provided name rather than the type's default. </p>
<h2 id="CommonType">type <span>CommonType</span>  </h2> <p>CommonType holds elements of all types. It is a historical artifact, kept for binary compatibility and exported only for the benefit of the package's encoding of type descriptors. It is not intended for direct use by clients. </p>
<pre data-language="go">type CommonType struct {
    Name string
    Id   typeId
}
</pre> <h2 id="Decoder">type <span>Decoder</span>  </h2> <p>A Decoder manages the receipt of type and data information read from the remote side of a connection. It is safe for concurrent use by multiple goroutines. </p>
<p>The Decoder does only basic sanity checking on decoded input sizes, and its limits are not configurable. Take caution when decoding gob data from untrusted sources. </p>
<pre data-language="go">type Decoder struct {
    // contains filtered or unexported fields
}
</pre> <h3 id="NewDecoder">func <span>NewDecoder</span>  </h3> <pre data-language="go">func NewDecoder(r io.Reader) *Decoder</pre> <p>NewDecoder returns a new decoder that reads from the <span>io.Reader</span>. If r does not also implement <span>io.ByteReader</span>, it will be wrapped in a <span>bufio.Reader</span>. </p>
<h3 id="Decoder.Decode">func (*Decoder) <span>Decode</span>  </h3> <pre data-language="go">func (dec *Decoder) Decode(e any) error</pre> <p>Decode reads the next value from the input stream and stores it in the data represented by the empty interface value. If e is nil, the value will be discarded. Otherwise, the value underlying e must be a pointer to the correct type for the next data item received. If the input is at EOF, Decode returns <span>io.EOF</span> and does not modify e. </p>
<h3 id="Decoder.DecodeValue">func (*Decoder) <span>DecodeValue</span>  </h3> <pre data-language="go">func (dec *Decoder) DecodeValue(v reflect.Value) error</pre> <p>DecodeValue reads the next value from the input stream. If v is the zero reflect.Value (v.Kind() == Invalid), DecodeValue discards the value. Otherwise, it stores the value into v. In that case, v must represent a non-nil pointer to data or be an assignable reflect.Value (v.CanSet()) If the input is at EOF, DecodeValue returns <span>io.EOF</span> and does not modify v. </p>
<h2 id="Encoder">type <span>Encoder</span>  </h2> <p>An Encoder manages the transmission of type and data information to the other side of a connection. It is safe for concurrent use by multiple goroutines. </p>
<pre data-language="go">type Encoder struct {
    // contains filtered or unexported fields
}
</pre> <h3 id="NewEncoder">func <span>NewEncoder</span>  </h3> <pre data-language="go">func NewEncoder(w io.Writer) *Encoder</pre> <p>NewEncoder returns a new encoder that will transmit on the <span>io.Writer</span>. </p>
<h3 id="Encoder.Encode">func (*Encoder) <span>Encode</span>  </h3> <pre data-language="go">func (enc *Encoder) Encode(e any) error</pre> <p>Encode transmits the data item represented by the empty interface value, guaranteeing that all necessary type information has been transmitted first. Passing a nil pointer to Encoder will panic, as they cannot be transmitted by gob. </p>
<h3 id="Encoder.EncodeValue">func (*Encoder) <span>EncodeValue</span>  </h3> <pre data-language="go">func (enc *Encoder) EncodeValue(value reflect.Value) error</pre> <p>EncodeValue transmits the data item represented by the reflection value, guaranteeing that all necessary type information has been transmitted first. Passing a nil pointer to EncodeValue will panic, as they cannot be transmitted by gob. </p>
<h2 id="GobDecoder">type <span>GobDecoder</span>  </h2> <p>GobDecoder is the interface describing data that provides its own routine for decoding transmitted values sent by a GobEncoder. </p>
<pre data-language="go">type GobDecoder interface {
    // GobDecode overwrites the receiver, which must be a pointer,
    // with the value represented by the byte slice, which was written
    // by GobEncode, usually for the same concrete type.
    GobDecode([]byte) error
}</pre> <h2 id="GobEncoder">type <span>GobEncoder</span>  </h2> <p>GobEncoder is the interface describing data that provides its own representation for encoding values for transmission to a GobDecoder. A type that implements GobEncoder and GobDecoder has complete control over the representation of its data and may therefore contain things such as private fields, channels, and functions, which are not usually transmissible in gob streams. </p>
<p>Note: Since gobs can be stored permanently, it is good design to guarantee the encoding used by a GobEncoder is stable as the software evolves. For instance, it might make sense for GobEncode to include a version number in the encoding. </p>
<pre data-language="go">type GobEncoder interface {
    // GobEncode returns a byte slice representing the encoding of the
    // receiver for transmission to a GobDecoder, usually of the same
    // concrete type.
    GobEncode() ([]byte, error)
}</pre><div class="_attribution">
  <p class="_attribution-p">
    &copy; Google, Inc.<br>Licensed under the Creative Commons Attribution License 3.0.<br>
    <a href="http://golang.org/pkg/encoding/gob/" class="_attribution-link">http://golang.org/pkg/encoding/gob/</a>
  </p>
</div>