Go

What is the difference between a type conversion and a type assertion?

Question 9MediumGo 1.22 to 1.25

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

All 39 Language Fundamentals & Types questions