Go has no type casting. It has explicit type conversion, written T(x), which converts a value to type T when the language rules allow it. Conversions between numeric types, between strings and byte or rune slices, and between types with identical underlying types are checked by the compiler, and Go never converts types implicitly.
"Casting" in C or C++ can reinterpret memory or silently coerce values. In Go, the related but different operation for interface values is a type assertion. This article covers numeric, string, struct and slice conversions, strconv for parsing text, and the pitfalls of truncation and overflow.
A conversion has the form T(expression). Even between closely related types, Go requires you to write it out.
The explicit rule removes a whole class of bugs where mixed-type arithmetic quietly changes results. It also means that int and int64 are different types even when they have the same size on your platform.
Conversions between numeric types are always allowed, but they can lose information.
Rules to remember:
math.Round first if you want rounding.uint8(300).Strings are immutable byte sequences, and these conversions copy data.
Be careful with string(i) where i is an integer: it produces the character with that code point, not the decimal digits. For example, string(rune(65)) is "A". The go vet tool warns about string(int) conversions. To get digits, use strconv.Itoa(65) or fmt.Sprint(65).
Converting between text and numbers is not a language conversion. Use the strconv package, which returns errors for invalid input.
Two types are convertible when they have identical underlying types. For structs, the field names, types and order must match, and struct tags are ignored in the comparison.
Defined types such as Celsius stop you from mixing units by accident, and conversion is the deliberate step that crosses the boundary. A slice can also be converted to an array or array pointer (Go 1.17 and 1.20), and panics if the slice is too short.
Conversion changes a value to another static type. A type assertion recovers the concrete type held inside an interface value.
Use the two-value form, or a type switch, when you are not certain of the dynamic type.
Not as in C. Go has explicit conversions with T(x) and type assertions for interfaces. Neither reinterprets raw memory; for that you need the unsafe package.
Use strconv.Atoi or strconv.ParseInt. A plain conversion such as int("12") does not compile.
string(65) converts the integer to the character with that Unicode code point. Use strconv.Itoa to get the decimal text.
No. It truncates toward zero. Call math.Round before converting if you need rounding.
Go uses explicit conversions with T(x), never implicit ones. Watch for truncation and wrapping in numeric conversions, use strconv for text and numbers, convert between struct types only when their underlying types are identical, and use type assertions to recover concrete types from interfaces.