go-gorm/gorm · error

failed to unmarshal gob value: %#v

Error message

failed to unmarshal gob value: %#v

What it means

GobSerializer.Scan decodes database bytes back into the struct field using encoding/gob. It only accepts dbValue of type []byte; any other driver value (string, nil-adjacent types, int) fails fast with 'failed to unmarshal gob value' showing the received value. Note: SQL NULL (nil) is allowed and skips decoding; the failure is for non-nil, non-[]byte values.

Source

Thrown at schema/serializer.go:173

		err = fmt.Errorf("invalid field type %#v for UnixSecondSerializer, only int, uint supported", fieldValue)
	}
	return
}

// GobSerializer gob serializer
type GobSerializer struct{}

// Scan implements serializer interface
func (GobSerializer) Scan(ctx context.Context, field *Field, dst reflect.Value, dbValue interface{}) (err error) {
	fieldValue := reflect.New(field.FieldType)

	if dbValue != nil {
		var bytesValue []byte
		switch v := dbValue.(type) {
		case []byte:
			bytesValue = v
		default:
			return fmt.Errorf("failed to unmarshal gob value: %#v", dbValue)
		}
		if len(bytesValue) > 0 {
			decoder := gob.NewDecoder(bytes.NewBuffer(bytesValue))
			err = decoder.Decode(fieldValue.Interface())
		}
	}
	field.ReflectValueOf(ctx, dst).Set(fieldValue.Elem())
	return
}

// Value implements serializer interface
func (GobSerializer) Value(ctx context.Context, field *Field, dst reflect.Value, fieldValue interface{}) (interface{}, error) {
	buf := new(bytes.Buffer)
	err := gob.NewEncoder(buf).Encode(fieldValue)
	return buf.Bytes(), err
}

View on GitHub (pinned to 1d6ce99528)

Solutions

  1. Ensure the column type returns bytes — use BLOB/VARBINARY rather than TEXT/CHAR.
  2. Avoid casting the column in raw SQL selects.
  3. If the driver insists on strings, switch that field to a custom serializer that converts string → []byte before gob-decoding.

Example fix

// before
Meta map[string]any `gorm:"serializer:gob;type:text"` // driver returns string

// after
Meta map[string]any `gorm:"serializer:gob;type:blob"`
Defensive patterns

Strategy: fallback

Try / catch

if err := db.Find(&items).Error; err != nil {
    if strings.Contains(err.Error(), "failed to unmarshal gob value") {
        return fmt.Errorf("gob column came back as %T; ensure column type is binary (BLOB) and not cast in SQL", err)
    }
    return err
}

Prevention

When it happens

Trigger: A `gorm:"serializer:gob"` column read back as a string (some drivers/TEXT columns return string), or a query casting the column (e.g. SELECT CAST(col AS CHAR)) so the driver no longer returns bytes.

Common situations: Switching drivers (MySQL TEXT vs BLOB, SQLite text affinity) where the same column arrives as string; raw SQL projections changing column types; proxy/middleware rewriting results.

Related errors


AI-assisted analysis of go-gorm/gorm@1d6ce99528 (2026-08-15). Data as JSON: /api/errors/b780f4e94c979646. Report an issue: GitHub.