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.
Code
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
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.