JSON Marshal Rejects Channels And Funcs

json.Marshal fails on chan and func fields: errors.As recovers *json.UnsupportedTypeError naming the exact Go type, so the wire keeps only encodable data.

GoData Integrity

Code

gosnippet
30 lines
package main

import (
	"encoding/json"
	"errors"
	"fmt"
)

type Job struct {
	Name   string
	Done   chan struct{} // channel 无法编码成 JSON
	Format func()        // 函数同样不行
}

func main() {
	job := Job{Name: "index", Done: make(chan struct{})}

	_, err := json.Marshal(job)
	fmt.Println("marshal failed:", err != nil)

	// 错误是 *json.UnsupportedTypeError,errors.As 取出出错的具体 Go 类型
	var ute *json.UnsupportedTypeError
	if errors.As(err, &ute) {
		fmt.Println("type:", ute.Type)
	}

	// 修复:通道和函数留在内部结构里,序列化边界只暴露可编码数据
	wire, _ := json.Marshal(struct{ Name string }{Name: job.Name})
	fmt.Println("wire:", string(wire))
}

Inside the snippet

JSON Marshal Rejects Channels And Funcs is built around the function main.

Points of care

  • No package manager involved — every call resolves to a built-in API.

Putting it to use

Signature: func main()

The file announces its steps in the output: marshal failed:, type:, wire:.

Lines worth quoting

job := Job{Name: "index", Done: make(chan struct{})}
if errors.As(err, &ute) {
	fmt.Println("type:", ute.Type)
}

Interactive Tools for This Topic

FAQ

What does JSON Marshal Rejects Channels And Funcs print when run?
Invoke the file as-is — the `marshal failed:`, `type:`, `wire:` prefixes identify which step printed each line.