Switch Type Assertions On Any

Consume untyped values safely with a type switch, giving each concrete type its own branch while rejecting unexpected shapes loudly.

GoData Integrity

Code

gosnippet
28 lines
package main

import "fmt"

func describe(v any) string {
	// type switch:一次遍历按具体类型分派
	switch value := v.(type) {
	case string:
		return "text of length " + fmt.Sprint(len(value))
	case int:
		if value < 0 {
			return "negative int"
		}
		return "non-negative int"
	case []int:
		return fmt.Sprintf("int slice of %d items", len(value))
	case error:
		return "error: " + value.Error()
	default:
		return fmt.Sprintf("unsupported type %T", v)
	}
}

func main() {
	for _, v := range []any{"config", 42, -3, []int{1, 2}, fmt.Errorf("boom"), 3.14} {
		fmt.Println(describe(v))
	}
}

Going over the source

Count the functions describe and main as the entire surface area of Switch Type Assertions On Any.

Repetition is confined to for _, v := range []any{"config", 42, -3, []int{1, 2}, fmt.Errorf("boom"), 3.14} — the rest of the file is straight-line.

Applying it

Entry signature: func describe(v any) string

main sequences describe; executing the file runs that flow once.

Statements that matter

for _, v := range []any{"config", 42, -3, []int{1, 2}, fmt.Errorf("boom"), 3.14} {
fmt.Println(describe(v))
}
return fmt.Sprintf("int slice of %d items", len(value))
return fmt.Sprintf("unsupported type %T", v)

Interactive Tools for This Topic

FAQ

How do you run Switch Type Assertions On Any?
Run the file on its own; every call resolves against the standard surface it already imports.