Skip to content

len() Builtin

The len() builtin returns the length of arrays, maps, and strings.

  • Signature: len(value any) -> int
  • Supported types: arrays, maps, strings
  • Strict behavior: calling len(None) or len() with unsupported types raises a runtime error.

Quick examples

Quick Examples
package main
import fmt

function main() {
    // Arrays
    var a = [1, 2, 3]
    fmt.Println(len(a))      // 3

    // Maps
    var m = {"a": 1, "b": 2}
    fmt.Println(len(m))      // 2

    // Strings
    var s = "hello"
    fmt.Println(len(s))      // 5
}

Strict error behavior

The builtin performs strict type checking. If called with None or any unsupported type, it raises a runtime error.

len() Examples
1
2
3
4
5
6
7
8
9
package main
import fmt

function main() {
    var x = None
    // This raises a runtime error:
    // "len() argument must be an array, map, or string, got NULL"
    fmt.Println(len(x))
}

Common unsupported arguments: - Integers, floats, booleans - Structs without a string representation as a sequence - None (strictly rejected)

Practical patterns

  • Array bounds and iteration:

    Array Bounds and Iteration
    1
    2
    3
    for i in range(len(a)) {
        // ...
    }
    

  • Map size checks:

    Map Size Checks
    1
    2
    3
    if len(m) == 0 {
        fmt.Println("map is empty")
    }
    

  • String processing:

    String Processing
    if len(s) > 80 { /* wrap */ }
    

Notes

  • Behavior mirrors the language’s strict runtime type validation. Use explicit conditionals to check for None before calling len when inputs may be missing.