Type conversion
- Go course
- Beginner
- Lesson 22/90
- 4 min
Learn explicit type conversion in Go.
Type conversion
Go doesn't mix different number types on its own; adding an int and a float64 is a compile error. Conversion is written explicitly as Type(value):
adet := 3
fiyat := 12.5
toplam := float64(adet) * fiyat // 37.5
tam := int(toplam) // 37 (fraction dropped)An int() conversion doesn't round; it cuts off the fraction.
Number and text conversion
string(65) gives the character with code 65 ("A"), not "65". To turn numbers into text and text into numbers use the strconv package:
s := strconv.Itoa(42) // "42"
n, err := strconv.Atoi("17") // 17, nil
_, err = strconv.Atoi("on") // error: invalid syntaxBecause Atoi can return an error, its result is always checked.
Practice Compute an average
Declare toplam := 17 and adet := 4. Compute the average with a float64 conversion and print it with fmt.Printf("%.2f\n", ortalama).
Starter code
package main
import "fmt"
func main() {
// buraya yaz
}Sample solution
package main
import "fmt"
func main() {
toplam := 17
adet := 4
ortalama := float64(toplam) / float64(adet)
fmt.Printf("%.2f\n", ortalama)
}Expected output
4.25
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is <code>int(9.99)</code>?
- An error
- 9 Correct answer
- 10
- 9.99
Explanation: Converting a decimal to an integer truncates toward zero; use math.Round to round.
2 Convert to decimal
ortalama := ____(toplam) / float64(adet)
ortalama := float64(toplam) / float64(adet)
Explanation: Converting to float64 before dividing keeps the decimal result.
3 Conversion and result
| Term | Meaning |
|---|---|
float64(3) |
3.0 |
int(7.8) |
7 |
strconv.Itoa(5) |
"5" |
string(rune(65)) |
"A" |