Go: Cast vs Conversion by Example
Casting and conversion are often confusing. In order to have a better understanding of them, we will take an example of each.
Go only works with conversion, and all the rules are defined in the Go specification.
Conversion with integers
Let’s start with the conversion of a positive signed integer. The specification defines some rules regarding the integers:
if the value is a signed integer, it is sign extended to implicit infinite precision; otherwise it is zero extended. It is then truncated to fit in the result type’s size
Our example will convert a signed integer to an integer with a smaller size, to an unsigned integer, and finally to an integer with bigger size.
var a int16 = 511fmt.Printf("cast int8: %d\n", int8(a))
fmt.Printf("cast uint8: %d\n", uint8(a))
fmt.Printf("cast int32: %d\n", int32(a))--------------
cast int8: -1
cast uint8: 255
cast int32: 511
source: https://play.golang.org/p/u9F9KYhiEtU
The bits conversion from the int16 to int8 is the following: