What is the difference between a type conversion and a type assertion?
A conversion, T(x), is checked at compile time: the compiler rejects it unless the types are convertible. It may still do work at run time, such as copying bytes for []byte(s), truncating a float, or panicking when a slice is too short for the target array. Valid conversions include: between numeric types, between types with the same underlying type, between strings and byte or rune slices, from a slice to an array pointer (Go 1.17+), and from a slice to an array (Go 1.20+).
A type assertion, x.(T), happens at run time and only works on interface values. It pulls out the concrete value stored in the interface (when T is a concrete type), or checks whether that value also satisfies another interface (when T is an interface).
f := 3.9
n := int(f) // conversion: 3 (truncates toward zero)
var v any = "hello"
s := v.(string) // assertion OK
// i := v.(int) // panics: interface conversion: interface {} is string, not int
i, ok := v.(int) // comma-ok form: 0, false, no panic
var w io.Writer = os.Stdout
if sw, ok := w.(io.StringWriter); ok { // interface-to-interface check
sw.WriteString("hi\n")
}
nums := []int{1, 2, 3, 4}
arr := [3]int(nums[:3]) // Go 1.20: slice-to-array conversion, panics if len < 3
Gotchas: int(v) on an any value does not compile, because you need an assertion. Converting a large float64 to int gives an implementation-defined result when the value doesn't fit. What the interviewer wants to hear: always use the comma-ok form unless a panic really means a programming bug.
More on Language Fundamentals & Types
- Q7What are the rules for
:=redeclaration, and why does this not compile? - Q8What does this print? (Assignment evaluation order)
- Q10In a type switch, what is the type of the bound variable when a case lists several types, and how does
case nilbehave? - 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?