DEV Community

Cover image for Go Type Casting: Starter Guide
Younis Jad
Younis Jad

Posted on

Go Type Casting: Starter Guide

There are two ways of converting types in Go: Implicit conversion and Explicit conversion.

Implicit Conversion

Implicit conversionImplicit conversion occurs when Go converts the type of a value automatically. For instance, when we assign an integer value to a float variable, Go will automatically convert it to a float type. Here is an example of implicit conversion:

package main

import "fmt"

func main() {
  var a float32 = 5.6
  var b float64 = a

  fmt.Printf("a = %v, b = %v\n", a, b)
}
Enter fullscreen mode Exit fullscreen mode

Explicit conversion

Explicit conversion occurs when we use the casting syntax to convert a value to a different type. The casting syntax in Go is similar to other programming languages, as it requires enclosing the value in parentheses and specifying the type in front of them. Here is an example of explicit conversion:

package main

import "fmt"

func main() {
  var a float64 = 5.6
  var b int = int(a)

  fmt.Printf("a = %v, b = %v\n", a, b)
}
Enter fullscreen mode Exit fullscreen mode

In the code above, the value of variable a is explicitly cast to an integer, and it is assigned to variable b. The int function is used to perform the type conversion, and the resulting value is truncated to an integer.

Continue Reading

Top comments (0)