In a type switch, what is the type of the bound variable when a case lists several types, and how does case nil behave?
Question 10HardGo 1.22 to 1.25
func describe(x any) string {
switch v := x.(type) {
case nil:
return "nil interface"
case int, int64:
// v has type any here, NOT int
return fmt.Sprintf("integer %v", v)
case string:
return "string of len " + strconv.Itoa(len(v)) // v is a string
case error:
return "error: " + v.Error()
case fmt.Stringer:
return "stringer: " + v.String()
default:
return fmt.Sprintf("other %T", v)
}
}
Rules:
- If a case lists exactly one type,
vhas that type. - If a case lists several types, or in
default,vkeeps the type of the switch expression (hereany). Sov + 1would not compile incase int, int64. case nilmatches only when the interface itself is nil. An interface that holds a(*T)(nil)does not match it.- Cases are checked in order. Put more specific interfaces (such as
error) before broader ones. A type that implements botherrorandStringergoes to whichever case comes first. fallthroughis not allowed in a type switch.
More on Language Fundamentals & Types
- Q8What does this print? (Assignment evaluation order)
- Q9What is the difference between a type conversion and a type assertion?
- Q11How are strings represented in Go? What does this print?
- Q12What happens when you range over invalid UTF-8, and what does
string(65)produce? - Q13What does converting between
stringand[]bytecost, and how do you build strings efficiently? - Q14When are the arguments to a deferred call evaluated? What does this print?