go type_error ai_generated true

error: json: unsupported type: chan int

ID: go/encoding-json-marshal-unsupported-type

Also available as: JSON · Markdown · 中文
80%Fix Rate
82%Confidence
0Evidence
2024-11-15First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.20 active
1.21 active

Root Cause

Attempting to marshal a Go type that is not supported by encoding/json, such as channels, functions, or complex numbers.

generic

中文

尝试对 encoding/json 不支持的Go类型进行编组,例如通道、函数或复数。

Workarounds

  1. 90% success Implement json.Marshaler interface for the custom type
    type MyChan chan int
    func (c MyChan) MarshalJSON() ([]byte, error) {
        return json.Marshal(len(c))
    }

Dead Ends

Common approaches that don't work:

  1. Using reflect to manually marshal 60% fail

    Complex and error-prone; better to implement json.Marshaler interface.