Golang Tutorial

Fundamentals

Control Statements

Functions & Methods

Structure

Arrays & Slices

String

Pointers

Interfaces

Concurrency

Type Casting in Go

Type casting, often referred to as type conversion in Go, allows you to convert a value from one type to another. Go doesn't allow implicit type conversion due to type mismatch; thus, explicit type conversion is required to change the type of a value. This tutorial will guide you through the essentials of type casting in Go.

1. Basic Type Conversion

In Go, you can convert between compatible types by using the target type as a function.

package main

import "fmt"

func main() {
    var i int = 42
    var f float64 = float64(i)
    
    fmt.Println(i)   // Outputs: 42
    fmt.Println(f)   // Outputs: 42 (but as a float64)
}

2. Converting to and from Strings

Go provides the strconv package for converting between numeric types and strings.

package main

import (
	"fmt"
	"strconv"
)

func main() {
    // int to string
    i := 42
    s := strconv.Itoa(i)
    fmt.Println(s)  // Outputs: "42"

    // string to int
    str := "57"
    intval, err := strconv.Atoi(str)
    if err == nil {
        fmt.Println(intval)  // Outputs: 57
    } else {
        fmt.Println("Error:", err)
    }
}

3. Type Assertion

In the context of interfaces, Go provides type assertion to retrieve the concrete value from an interface.

var x interface{} = "hello"

// Use a type assertion to get the string value:
s, ok := x.(string)
if ok {
    fmt.Println(s)  // Outputs: hello
} else {
    fmt.Println("Not a string")
}

// Forcing a type assertion without checking can panic:
s = x.(string)
fmt.Println(s)  // Outputs: hello

4. Converting Between Numeric Types

You can also convert between different numeric types, but be cautious of potential data loss or overflow.

var i int32 = 1000
var j int64 = int64(i)
fmt.Println(j)  // Outputs: 1000

var f float32 = 3.14
var g float64 = float64(f)
fmt.Println(g)  // Outputs: 3.140000104904175

5. Converting Arrays and Slices

Type conversion doesn't work directly for arrays and slices. However, you can manually create a new slice of the desired type and copy over the elements.

ints := []int{1, 2, 3}
floats := make([]float64, len(ints))

for i, v := range ints {
    floats[i] = float64(v)
}
fmt.Println(floats)  // Outputs: [1 2 3] (but as a []float64)

Key Takeaways:

  • Go doesn't allow implicit type conversion for mismatched types. You must explicitly convert them.
  • Use the target type as a function to perform basic type conversions.
  • The strconv package facilitates string conversions for numeric types.
  • Type assertions can extract the actual type from interface values.
  • Be cautious of data loss or overflows when converting between numeric types.

Always remember that type safety is one of Go's strong features. Be explicit with your conversions, and when working with different types, always handle potential errors.

  1. Type conversion in Go:

    Type conversion is the process of converting a value from one data type to another.

    package main
    
    import "fmt"
    
    func main() {
        var x int = 42
        var y float64 = float64(x)
        fmt.Printf("%d as float64 is %f\n", x, y)
    }
    
  2. Type assertion vs type conversion in Golang:

    Type conversion is used to convert between compatible types, while type assertion is used to access the underlying concrete value in an interface.

    package main
    
    import "fmt"
    
    func main() {
        var i interface{} = 42
    
        // Type assertion
        x, ok := i.(int)
        if ok {
            fmt.Println("Type assertion result:", x)
        }
    
        // Type conversion
        y := float64(x)
        fmt.Println("Type conversion result:", y)
    }
    
  3. Explicit type casting in Go:

    Explicit type casting is the process of explicitly converting a value from one type to another.

    package main
    
    import "fmt"
    
    func main() {
        var x int = 42
        var y float64 = float64(x)
        fmt.Printf("%d as float64 is %f\n", x, y)
    }
    
  4. Golang convert string to int:

    Converting a string to an integer in Go can be done using the strconv package.

    package main
    
    import (
        "fmt"
        "strconv"
    )
    
    func main() {
        str := "42"
        num, err := strconv.Atoi(str)
        if err == nil {
            fmt.Println("Converted string to int:", num)
        } else {
            fmt.Println("Conversion error:", err)
        }
    }
    
  5. Type casting interfaces in Go:

    Type casting an interface involves asserting its underlying type.

    package main
    
    import "fmt"
    
    type Shape interface {
        Area() float64
    }
    
    type Circle struct {
        Radius float64
    }
    
    func (c Circle) Area() float64 {
        return 3.14 * c.Radius * c.Radius
    }
    
    func main() {
        var s Shape = Circle{Radius: 2}
    
        // Type casting
        circle, ok := s.(Circle)
        if ok {
            fmt.Println("Circle area:", circle.Area())
        }
    }
    
  6. Type casting pointers in Golang:

    Type casting pointers involves converting pointers of one type to another.

    package main
    
    import "fmt"
    
    type Dog struct {
        Name string
    }
    
    type Animal struct {
        Name string
    }
    
    func main() {
        dog := Dog{Name: "Buddy"}
    
        // Type casting pointers
        var animalPtr *Animal = (*Animal)(&dog)
        fmt.Println("Animal name:", animalPtr.Name)
    }
    
  7. Type casting in switch statements Go:

    Type casting within switch statements is often used to handle different types.

    package main
    
    import "fmt"
    
    func processValue(value interface{}) {
        switch v := value.(type) {
        case int:
            fmt.Println("Integer:", v)
        case string:
            fmt.Println("String:", v)
        default:
            fmt.Println("Unknown type")
        }
    }
    
    func main() {
        processValue(42)
        processValue("Hello")
    }
    
  8. Type casting in Go examples:

    Additional examples showcasing type casting in various scenarios.

    package main
    
    import (
        "fmt"
        "strconv"
    )
    
    func main() {
        // Example 1: Type conversion
        var x int = 42
        var y float64 = float64(x)
        fmt.Printf("%d as float64 is %f\n", x, y)
    
        // Example 2: String to int
        str := "42"
        num, err := strconv.Atoi(str)
        if err == nil {
            fmt.Println("Converted string to int:", num)
        } else {
            fmt.Println("Conversion error:", err)
        }
    
        // Example 3: Type casting pointers
        type Dog struct {
            Name string
        }
    
        type Animal struct {
            Name string
        }
    
        dog := Dog{Name: "Buddy"}
        var animalPtr *Animal = (*Animal)(&dog)
        fmt.Println("Animal name:", animalPtr.Name)
    }