Convert between numeric types in Go
Explicit conversion syntax
Go does not automatically convert between different typed numeric values in ordinary assignment. Use T(x) to convert x to type T when permitted. Converting a floating-point value to an integer discards the fractional part toward zero. It does not round to the nearest integer.
package main
import "fmt"
func main() { x := 7.9 y := -7.9 fmt.Println(int(x), int(y))}The output is 7 -7. For integer-to-integer conversions, Go extends the source value as needed and truncates it to the destination width. This can change the number. Constant conversions must instead meet representability rules at compile time.
Narrowing is not validation
package main
import "fmt"
func main() { n := 300 fmt.Println(uint8(n))}The output is 44 because only the low eight bits remain (300 modulo 256). uint8(300) with a constant is a compile-time error. Before converting a runtime integer to uint8, check that it is between 0 and 255; conditions are taught in later lessons. For floating-to-integer conversions, also reject non-finite or out-of-range values before converting: when the result cannot be represented, the implementation determines the result. Do not rely on a particular wrapped result for those cases.
Try it locally
Declare a float64 measurement of -12.75 and convert it to int. Declare an int count of 260 and convert it to uint8. Print the two results. Expected: -12 4. Hint: the two conversions follow different rules.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Constants and Basic Types 07: Convert between numeric types in Go
Check the lesson objective before moving on.
For x := -3.8, what is int(x)?
Why is uint8(300) invalid when 300 is a constant?