go-redis/redis · error

redis: unexpected type=%T for Slice

Error message

redis: unexpected type=%T for Slice

What it means

Returned by Cmd.Slice() (command.go:778) when the reply value is not []interface{}. Slice() expects an array reply already coerced to a Go slice; any scalar type (string, int64, bool, nil) yields this error. Indicates the command did not return an array, or the wrong accessor was used.

Source

Thrown at command.go:787

		return val != 0, nil
	case string:
		return strconv.ParseBool(val)
	default:
		err := fmt.Errorf("redis: unexpected type=%T for Bool", val)
		return false, err
	}
}

func (cmd *Cmd) Slice() ([]interface{}, error) {
	cmd.await()
	if cmd.err != nil {
		return nil, cmd.err
	}
	switch val := cmd.val.(type) {
	case []interface{}:
		return val, nil
	default:
		return nil, fmt.Errorf("redis: unexpected type=%T for Slice", val)
	}
}

func (cmd *Cmd) StringSlice() ([]string, error) {
	slice, err := cmd.Slice()
	if err != nil {
		return nil, err
	}

	ss := make([]string, len(slice))
	for i, iface := range slice {
		val, err := toString(iface)
		if err != nil {
			return nil, err
		}
		ss[i] = val
	}
	return ss, nil

View on GitHub (pinned to 36d97525cd)

Solutions

  1. Use the typed command method that returns the correct slice shape (LRange → StringSliceCmd; ZRange → StringSliceCmd).
  2. Type-switch on cmd.Result() when using Do.
  3. Handle redis.Nil and empty-array cases explicitly before calling Slice().

Example fix

// before
v, err := client.Do(ctx, "LRANGE", "q", 0, -1).Slice()

// after
elems, err := client.LRange(ctx, "q", 0, -1).Result()
Defensive patterns

Strategy: type-guard

Type guard

func asSlice(cmd *redis.Cmd) ([]interface{}, error) {
    if err := cmd.Err(); err != nil { return nil, err }
    if s, ok := cmd.Val().([]interface{}); ok {
        return s, nil
    }
    return nil, fmt.Errorf("not a slice: %T", cmd.Val())
}

Try / catch

s, err := cmd.Slice()
if err != nil && strings.Contains(err.Error(), "unexpected type") {
    // reply was not an array — switch to the typed accessor
}

Prevention

When it happens

Trigger: Calling Slice() on a Cmd whose reply is a scalar (e.g. Do INCR then Slice()); calling Slice() on a nil reply; using Slice() where the typed accessor (StringSliceCmd, Int64SliceCmd) is required.

Common situations: Generic Do Cmd mis-typed; expecting an array from a command that returns a scalar on a special case (e.g. LRANGE on a non-list returns WRONGTYPE, but a nil/empty case returns nil val); confusing redis.Nil with an empty array.

Related errors


AI-assisted analysis of go-redis/redis@36d97525cd (2026-08-06). Data as JSON: /data/errors/91fd68d935274d48.json. Report an issue: GitHub.