Ad Space — Top Banner

cannot range over

Go Compiler Error

Severity: Minor

What Does This Error Mean?

The Go 'cannot range over' error means you are using a range loop on a type that is not rangeable. Range works on arrays, slices, maps, strings, and channels. You cannot range over an integer, struct, or interface without type-asserting it first.

Affected Models

  • Go 1.x (all versions)

Common Causes

  • Using range on an integer variable instead of a slice
  • Ranging over a nil pointer or unexported interface
  • Using range on a struct that should be a slice of structs
  • Variable declared as interface{} holding a slice — must be type-asserted first
  • Attempting to range over a custom type with a non-rangeable underlying type

How to Fix It

  1. Check the type of the variable you are ranging over.

    The error message includes the type. If it says cannot range over x (type int), x is a number, not a slice. Ensure the variable holds a slice, array, map, string, or channel.

  2. If ranging over an interface{} or any, type-assert it first.

    Example: if items, ok := data.([]string); ok { for _, item := range items { ... } } An interface value must be asserted to its concrete slice type before ranging.

  3. To loop N times without a slice, use a traditional for loop.

    In Go 1.22+, you can write: for i := range 10 {} In earlier versions, use: for i := 0; i < n; i++ {} to loop a fixed number of times.

Frequently Asked Questions

Can you range over a map in Go?

Yes — ranging over a map gives key and value pairs on each iteration: for k, v := range myMap {} Note that map iteration order is randomised in Go — never assume a specific order.

Can you range over a channel in Go?

Yes — ranging over a channel reads values until the channel is closed: for v := range ch {} The loop exits when the channel is closed. If the channel is never closed, the loop blocks indefinitely.