dgraph-io/dgraph · error

invalid conversion %s to nil

Error message

invalid conversion %s to nil

What it means

types.Marshal returns this when the destination *Val is nil. Marshal writes the converted value through the destination pointer, so a nil target cannot receive the result. The error message names the source type (from.Tid.Name()) to help identify the call site.

Source

Thrown at types/conversion.go:483

				vc := BytesAsFloatArray(data)
				*res = vc
			case StringID:
				vc := BytesAsFloatArray(data)
				sa := FloatArrayAsString(vc)
				*res = sa
			default:
				return to, cantConvert(fromID, toID)
			}
		}
	default:
		return to, cantConvert(fromID, toID)
	}
	return to, nil
}

func Marshal(from Val, to *Val) error {
	if to == nil {
		return errors.Errorf("invalid conversion %s to nil", from.Tid.Name())
	}

	fromID := from.Tid
	toID := to.Tid
	val := from.Value
	res := &to.Value

	// This is a default value from sg.fillVars, don't convert it's empty.
	// Fixes issue #2980.
	if val == nil {
		*to = ValueForType(toID)
		return nil
	}

	switch fromID {
	case BinaryID:
		vc := val.([]byte)
		switch toID {

View on GitHub (pinned to 759e242be6)

Solutions

  1. Initialize the destination: out := &types.Val{Tid: types.StringID} (or the expected target type) before calling Marshal
  2. Check for nil before calling and return a caller-appropriate error
  3. Fix upstream functions that may return a nil *Val

Example fix

// before
var out *types.Val
types.Marshal(types.Val{Tid: types.StringID, Value: "x"}, out) // panics path / error
// after
out := &types.Val{Tid: types.StringID}
err := types.Marshal(types.Val{Tid: types.StringID, Value: "x"}, out)
Defensive patterns

Strategy: type-guard

Validate before calling

if out == nil {
    return errors.New("destination Val must be initialized before Marshal")
}
err := types.Marshal(from, out)

Type guard

func marshalSafe(from types.Val, to *types.Val) error {
    if to == nil { return errors.New("nil destination Val") }
    return types.Marshal(from, to)
}

Try / catch

var out *types.Val // may be nil from upstream
if err := types.Marshal(from, out); err != nil && strings.Contains(err.Error(), "to nil") {
    out = &types.Val{Tid: from.Tid}
    err = types.Marshal(from, out)
}

Prevention

When it happens

Trigger: Calling types.Marshal(from, nil) — commonly a nil *Val variable passed by mistake, or a function returning a nil *Val that is forwarded to Marshal.

Common situations: Refactors that changed a Val value to a *Val pointer left nil on early-return paths; structs holding *Val fields that were never initialized.

Related errors


AI-assisted analysis of dgraph-io/dgraph@759e242be6 (2026-09-01). Data as JSON: /api/errors/a0f5cb2c14945625. Report an issue: GitHub.