Gob Registers Interface Field Types

Encode interface-valued fields with gob by registering each concrete type, so the decoder can rebuild the right variant from the transmitted name.

GoData Integrity

Code

gosnippet
49 lines
package main

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

// Event 接口字段要承载的类型族
type Event interface{ Kind() string }

type Deploy struct{ Service string }
type Rollback struct{ Service string }

func (Deploy) Kind() string   { return "deploy" }
func (Rollback) Kind() string { return "rollback" }

// Register 建立具体类型名到类型的映射:接口字段的编解码都依赖它,
// 接收方必须注册同一组类型,否则解码接口字段会失败
func init() {
	gob.Register(Deploy{})
	gob.Register(Rollback{})
}

type Envelope struct {
	Event Event
}

func main() {
	var wire bytes.Buffer
	encoder := gob.NewEncoder(&wire)
	for _, env := range []Envelope{{Deploy{"billing"}}, {Rollback{"auth"}}} {
		if err := encoder.Encode(env); err != nil {
			fmt.Println("encode:", err)
			return
		}
	}

	decoder := gob.NewDecoder(&wire)
	for range 2 {
		var env Envelope
		if err := decoder.Decode(&env); err != nil {
			fmt.Println("decode:", err)
			return
		}
		fmt.Printf("decoded %s: %+v
", env.Event.Kind(), env.Event)
	}
}

A step-by-step pass over the file

Every piece of logic sits in the functions Kind, init and main.

Iteration happens inside for _, env := range []Envelope{{Deploy{"billing"}}, {Rollback{"auth"}}} — everything outside it runs once. Nothing falls through silently — 2 checkpoints test err != nil on the way through.

Caveats

  • There is nothing to install — the snippet never leaves the standard library.

Applying it

The entry-point signature is func (Deploy) Kind() string

The run emits 2 labeled sections — decoded deploy:, decoded rollback: — one per step; the encode: / decode: labels only appear on the error branches when err != nil, which the success path never triggers.

main sequences Kind; executing the file runs that flow once.

Statements that matter

func (Rollback) Kind() string { return "rollback" }
func (Deploy) Kind() string   { return "deploy" }
for _, env := range []Envelope{{Deploy{"billing"}}, {Rollback{"auth"}}} {
	if err := encoder.Encode(env); err != nil {
		fmt.Println("encode:", err)
		return
	}
}

Interactive Tools for This Topic

FAQ

What does Gob Registers Interface Field Types print when run?
Invoke the file as-is — the `encode:`, `decode:` prefixes identify which step printed each line.