๐ŸŽ“ A1Learner
๐Ÿ”
0 of 38 lessons completed

Go Type Conversion

Type conversion is the change of a value from one type to another type. Go converts a value only when the code names the new type.

An int becomes a float

The conversion float64(7) makes a float64 from the int 7. The division then keeps its decimal part and gives 3.5.

package main

import "fmt"

func main() {
	fmt.Println(float64(7) / 2)
}

A float becomes an int

A float variable holds 9.99 here. The conversion int(score) drops the decimal part and gives 9.

package main

import "fmt"

func main() {
	score := 9.99
	fmt.Println(int(score))
}

A code becomes a character

The conversion string(65) turns the code 65 into a character. The program prints the letter A.

package main

import "fmt"

func main() {
	fmt.Println(string(65))
}

Text cannot convert to a number

A string constant holds text, not a number. The compiler refuses this conversion and prints the error line below.

package main

import "fmt"

func main() {
	n := int("42")
	fmt.Println(n)
}

Example

package main

import "fmt"

func main() {
	celsius := 25
	fahrenheit := float64(celsius)*9/5 + 32
	fmt.Println("Celsius:", celsius)
	fmt.Println("Fahrenheit:", fahrenheit)
}

Key points

  • A conversion writes the target type in parentheses before the value.
  • A conversion to float64 lets a division keep its decimal part.
  • A conversion to int drops the decimal part of a value.
  • A conversion to string turns a number code into its character.

In this example, celsius holds the int 25. The conversion float64(celsius) makes a float64 copy for the maths. The formula gives 77, and the two lines print the Celsius and Fahrenheit values.

Note

Go makes no conversion on its own. The code names each change of type.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Go Playground

Exercise

A variable named score holds 9.99. What does int(score) print?