Description

Decode decodes the stream from reader and stores the result in the value pointed to by v. v cannot be a nil pointer. v can also be a reflect.Value of a pointer.

Note that a pointer to a nil interface is not a nil pointer. If you do not know what type of stream it is, pass in a pointer to a nil interface. We will decode and store a value in that nil interface.

Sample usages:

// Decoding into a non-nil typed value
var f float32
err = codec.NewDecoder(r, handle).Decode(&f)

// Decoding into nil interface
var v interface{}
dec := codec.NewDecoder(r, handle)
err = dec.Decode(&v)

When decoding into a nil interface{}, we will decode into an appropriate value based on the contents of the stream:

- Numbers are decoded as float64, int64 or uint64.
- Other values are decoded appropriately depending on the type:
  bool, string, []byte, time.Time, etc
- Extensions are decoded as RawExt (if no ext function registered for the tag)

Configurations exist on the Handle to override defaults (e.g. for MapType, SliceType and how to decode raw bytes).

When decoding into a non-nil interface{} value, the mode of encoding is based on the type of the value. When a value is seen:

- If an extension is registered for it, call that extension function
- If it implements BinaryUnmarshaler, call its UnmarshalBinary(data []byte) error
- Else decode it based on its reflect.Kind

There are some special rules when decoding into containers (slice/array/map/struct). Decode will typically use the stream contents to UPDATE the container.

- A map can be decoded from a stream map, by updating matching keys.
- A slice can be decoded from a stream array,
  by updating the first n elements, where n is length of the stream.
- A slice can be decoded from a stream map, by decoding as if
  it contains a sequence of key-value pairs.
- A struct can be decoded from a stream map, by updating matching fields.
- A struct can be decoded from a stream array,
  by updating fields as they occur in the struct (by index).

When decoding a stream map or array with length of 0 into a nil map or slice, we reset the destination map or slice to a zero-length value.

However, when decoding a stream nil, we reset the destination container to its "zero" value (e.g. nil for slice/map, etc).

Decode is referenced in 0 repositories