Comma Ok Type Assertion On Interface
Extract concrete values from interface values with comma-ok assertions so a mismatched dynamic type falls into an error branch instead of a panic.
Code
package main
import "fmt"
func describe(v any) {
// 单返回值断言:类型不符会 panic(此处仅示意,不执行)
// n := v.(int)
// comma-ok 断言:类型不符得到零值 + ok=false,走错误分支
if n, ok := v.(int); ok {
fmt.Println("int:", n*2)
return
}
if s, ok := v.(string); ok {
fmt.Println("string of length:", len(s))
return
}
fmt.Printf("unsupported %T\n", v)
}
func main() {
for _, v := range []any{21, "hello", true} {
describe(v)
}
// 已知接口值里装的是什么时,comma-ok 是防御性写法
var out any = 3.14
if f, ok := out.(float64); ok {
fmt.Println("float:", f)
}
}How the snippet works
The operative logic lives in the functions describe and main — everything else is wiring.
Iteration happens inside for _, v := range []any{21, "hello", true} — everything outside it runs once.
Watch out for
- No third-party code is loaded at any point while this runs.
Applying it
Entry signature: func describe(v any)
Output lines are prefixed (int:, string of length:, unsupported), so every step’s outcome shows up in the output.
There are 1 call inside main — describe — executed top to bottom.
Statements that decide the outcome
for _, v := range []any{21, "hello", true} {
describe(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
- What does Comma Ok Type Assertion On Interface print when run?
- The script runs standalone; its 4 labeled outputs include `int:`, `string of length:`, `unsupported`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.