go-redis/redis · error

redis: unexpected type=%T for Int

Error message

redis: unexpected type=%T for Int

What it means

Returned by Cmd.Int() (command.go:661) when the reply value is neither int64 nor string. Int() accepts int64 (from an integer reply) and string (parsed via strconv.Atoi); anything else (array, nil, bulk-of-wrong-shape) yields this error. It signals the reply did not carry a single numeric scalar.

Source

Thrown at command.go:667

		return val, nil
	default:
		err := fmt.Errorf("redis: unexpected type=%T for String", val)
		return "", err
	}
}

func (cmd *Cmd) Int() (int, error) {
	cmd.await()
	if cmd.err != nil {
		return 0, cmd.err
	}
	switch val := cmd.val.(type) {
	case int64:
		return int(val), nil
	case string:
		return strconv.Atoi(val)
	default:
		err := fmt.Errorf("redis: unexpected type=%T for Int", val)
		return 0, err
	}
}

func (cmd *Cmd) Int64() (int64, error) {
	cmd.await()
	if cmd.err != nil {
		return 0, cmd.err
	}
	return toInt64(cmd.val)
}

func toInt64(val interface{}) (int64, error) {
	switch val := val.(type) {
	case int64:
		return val, nil
	case string:
		return strconv.ParseInt(val, 10, 64)

View on GitHub (pinned to 36d97525cd)

Solutions

  1. Use the typed command (e.g. client.Incr → IntCmd; client.Del → IntCmd) so the reply parser sets an int64 directly.
  2. Call cmd.Result() and type-switch on interface{} before converting.
  3. Verify cmd.Err() (including redis.Nil) before reading the value.

Example fix

// before
n, err := client.Do(ctx, "DBSIZE").Int() // DBSIZE is integer → ok, but a Do over a non-int reply is not

// after — typed accessor
n, err := client.DbSize(ctx).Result()
Defensive patterns

Strategy: type-guard

Type guard

func asInt(cmd *redis.Cmd) (int, error) {
    if err := cmd.Err(); err != nil { return 0, err }
    switch v := cmd.Val().(type) {
    case int64:
        return int(v), nil
    case string:
        return strconv.Atoi(v)
    default:
        return 0, fmt.Errorf("not an int: %T", v)
    }
}

Try / catch

n, err := cmd.Int()
if err != nil && strings.Contains(err.Error(), "unexpected type") {
    // reply was not an integer scalar — use the typed command
}

Prevention

When it happens

Trigger: Calling Int() on a raw Cmd whose reply is an array (e.g. Do EXEC on a pipeline reply) or nil; calling Int() where the command actually returns a status/bulk that is non-numeric; calling Int() after an INCR but on a Cmd that was reused for a different command type.

Common situations: Reusing the generic Cmd from Do for a multi-element reply; expecting an integer reply from a command that returns a count-in-array; forgetting to handle redis.Nil (which returns before this switch only if cmd.err was set — but a present non-integer val still falls through).

Related errors


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