Go Type Casting

Converting between different data types in Go

🔄 What is Go Type Casting?

Go type casting converts one data type to another. Unlike some languages, Go requires explicit conversion between types, ensuring type safety and preventing unexpected behavior in your programs.


package main

import "fmt"

func main() {
    var x int = 42
    var y float64 = float64(x)  // Convert int to float64
    
    fmt.Println("Integer:", x)
    fmt.Println("Float:", y)
}
                                    

Output:

Integer: 42
Float: 42

Common Type Conversions

🔢

Int to Float

Convert integers to floating point

var x int = 10
var y float64 = float64(x)
📉

Float to Int

Convert floats to integers (truncates)

var x float64 = 10.7
var y int = int(x)  // y = 10
📝

Number to String

Convert numbers to text using strconv

import "strconv"
s := strconv.Itoa(42)  // "42"
🔤

String to Number

Convert text to numbers using strconv

import "strconv"
i, _ := strconv.Atoi("42")

🔹 Basic Type Conversions

Converting between numeric types:

package main

import "fmt"

func main() {
    // Integer to float
    var intNum int = 42
    var floatNum float64 = float64(intNum)
    
    // Float to integer (truncates decimal)
    var price float64 = 19.99
    var wholePart int = int(price)
    
    // Between different int sizes
    var smallInt int8 = 100
    var bigInt int64 = int64(smallInt)
    
    fmt.Println("Int to float:", intNum, "->", floatNum)
    fmt.Println("Float to int:", price, "->", wholePart)
    fmt.Println("int8 to int64:", smallInt, "->", bigInt)
}

Output:

Int to float: 42 -> 42
Float to int: 19.99 -> 19
int8 to int64: 100 -> 100

🔹 String Conversions

Converting between strings and numbers using strconv package:

package main

import (
    "fmt"
    "strconv"
)

func main() {
    // Number to string
    age := 25
    ageStr := strconv.Itoa(age)  // Integer to ASCII
    
    price := 19.99
    priceStr := strconv.FormatFloat(price, 'f', 2, 64)
    
    // String to number
    numStr := "42"
    num, err := strconv.Atoi(numStr)  // ASCII to Integer
    if err != nil {
        fmt.Println("Error:", err)
    }
    
    floatStr := "3.14"
    floatNum, err := strconv.ParseFloat(floatStr, 64)
    if err != nil {
        fmt.Println("Error:", err)
    }
    
    fmt.Println("Age as string:", ageStr)
    fmt.Println("Price as string:", priceStr)
    fmt.Println("String to int:", numStr, "->", num)
    fmt.Println("String to float:", floatStr, "->", floatNum)
}

Output:

Age as string: 25
Price as string: 19.99
String to int: 42 -> 42
String to float: 3.14 -> 3.14

🔹 Boolean Conversions

Converting booleans to strings and handling string to boolean:

package main

import (
    "fmt"
    "strconv"
)

func main() {
    // Boolean to string
    isActive := true
    activeStr := strconv.FormatBool(isActive)
    
    // String to boolean
    boolStr := "false"
    boolVal, err := strconv.ParseBool(boolStr)
    if err != nil {
        fmt.Println("Error:", err)
    }
    
    // Different string values that parse to boolean
    trueValues := []string{"true", "1", "t", "T", "TRUE", "True"}
    falseValues := []string{"false", "0", "f", "F", "FALSE", "False"}
    
    fmt.Println("Boolean to string:", isActive, "->", activeStr)
    fmt.Println("String to boolean:", boolStr, "->", boolVal)
    
    fmt.Println("\nTrue values:")
    for _, val := range trueValues {
        parsed, _ := strconv.ParseBool(val)
        fmt.Printf("  %s -> %t\n", val, parsed)
    }
}

Output:

Boolean to string: true -> true
String to boolean: false -> false

True values:
  true -> true
  1 -> true
  t -> true
  T -> true
  TRUE -> true
  True -> true

🔹 Practical Example: User Input Calculator

Using type conversion in a real program:

package main

import (
    "fmt"
    "strconv"
)

func main() {
    var input1, input2, operator string
    
    fmt.Print("Enter first number: ")
    fmt.Scan(&input1)
    
    fmt.Print("Enter operator (+, -, *, /): ")
    fmt.Scan(&operator)
    
    fmt.Print("Enter second number: ")
    fmt.Scan(&input2)
    
    // Convert strings to numbers
    num1, err1 := strconv.ParseFloat(input1, 64)
    num2, err2 := strconv.ParseFloat(input2, 64)
    
    if err1 != nil || err2 != nil {
        fmt.Println("Error: Invalid number input")
        return
    }
    
    var result float64
    switch operator {
    case "+":
        result = num1 + num2
    case "-":
        result = num1 - num2
    case "*":
        result = num1 * num2
    case "/":
        if num2 != 0 {
            result = num1 / num2
        } else {
            fmt.Println("Error: Division by zero")
            return
        }
    default:
        fmt.Println("Error: Invalid operator")
        return
    }
    
    // Convert result back to string for formatted output
    resultStr := strconv.FormatFloat(result, 'f', 2, 64)
    fmt.Printf("Result: %s %s %s = %s\n", input1, operator, input2, resultStr)
}

Output:

Enter first number: 15.5
Enter operator (+, -, *, /): *
Enter second number: 2
Result: 15.5 * 2 = 31.00

🧠 Test Your Knowledge

Which function converts an integer to a string?