Data Types & Strict Casting
Go enforces an extremely strict type system. Unlike languages that automatically cast numeric types, Go requires explicit casting for every single conversion.
1 Go Primitives & Formatting Specifiers
Go primitives include boolean, numeric types (integers `int8`, `int32`, `int64`, unsigned `uint`, floats `float32`, `float64`), and string types.
Strict Type Conversions: Go does not perform implicit type casting. Even converting an `int32` to an `int64` requires an explicit type cast: `var longVal int64 = int64(int32Val)`. If you try to compile code that performs implicit conversions (like `int + float`), compilation will fail.
2 Cast Operations Code
Let's run a program demonstrating casting and type formatting check specifiers:
Go — Casting and Type Specifiers
▶ Run Code
package main
import "fmt"
func main() {
intVal := 42
floatVal := 5.5
// Explicit casting to double float64 before math operation
result := float64(intVal) * floatVal
fmt.Printf("Result value: %f\n", result)
// Investigating type metadata (%T formats type string)
fmt.Printf("Type of intVal: %T\n", intVal)
fmt.Printf("Type of floatVal: %T\n", floatVal)
}
3 Code Challenge
Challenge: Write a program that defines an integer representing score items, and a float representing total possible items. Perform a division operation to calculate the percentage. Cast variables explicitly to avoid compilation errors and print the result.