How to Convert Between Types in Go (Type Casting)

Go uses explicit type conversion syntax T(v) instead of casting, requiring compatible types and failing at compile time for incompatible conversions.

Go does not use type casting; it uses explicit type conversion syntax T(v) to convert a value v to type T.

// Convert string to int
s := "123"
n, err := strconv.Atoi(s)

// Convert int to string
i := 42
str := strconv.Itoa(i)

// Convert between numeric types
f := 3.14
i2 := int(f)

// Convert between slices and arrays
arr := [3]int{1, 2, 3}
slice := arr[:] // Convert array to slice

Type conversion requires the value to be convertible to the target type; incompatible types (like string to int directly) will cause a compile error.