Go · Level 3 Interfaces

Type Switches

Describe any value decoded from JSON with a Go type switch on an any value, handling null, bools, numbers, strings, lists and objects, where numbers are float64.

  • switch v := x.(type)
  • in each case, v has that type
  • JSON numbers decoded into any are float64

A type switch branches on the type inside an any: in switch v := x.(type), each case gives v that type. Trap: numbers decoded into any are float64, never int, so a case int never matches them.

switch v := x.(type) {
case string:
    return "text " + v
case float64:
    return fmt.Sprint("number ", v)
}

Write Describe(v any) string for decoded JSON values: nil → "null", a bool → "bool true", a number → "number 2.5", a string → "text hi", []any → "list of 2", map[string]any → "object with 2 fields".

solution.go
Test Suites Pending
Output