Type Conversion
Go never changes the type of a variable by itself. When you need a value as another type, you convert it. Write the new type's name, and put the value in parentheses after it.
In the Operators lesson, minutes * rate did not compile, because minutes is an int and rate is a float64. Converting minutes fixes it:
package main
import "fmt"
func main() {
minutes := 90
rate := 1.5
fmt.Println(float64(minutes) * rate)
}
Output:
135
float64(minutes) gives a new float64 value, 90.0. It does not change minutes, which is still an int.
Convert before you divide
The most common place for a conversion is a division. Here are three ways to work out the average of 20 and 31:
a := 20
b := 31
fmt.Println((a + b) / 2)
fmt.Println(float64((a + b) / 2))
fmt.Println(float64(a+b) / 2)
Output:
25
25
25.5
The first line is an integer division, so the .5 is lost. The second line looks like a fix, but it converts too late. (a + b) / 2 is worked out first, as integers, and gives 25. Converting 25 gives 25.0, which prints as 25. Only the third line is right: it converts the sum first, so the division is a float64 division.
From float64 to int
Converting a float64 to an int cuts off the decimal part. It does not round:
price := 25.9
loss := -2.7
fmt.Println(int(price), int(loss))
Output:
25 -2
25.9 became 25, not 26, and -2.7 became -2. The Math Functions lesson shows how to round instead.
Numbers and text
Converting between numbers and strings needs the strconv package ("string conversion"). strconv.Itoa turns an int into a string. Do not use string() for that. It treats the number as a character code:
package main
import (
"fmt"
"strconv"
)
func main() {
n := 65
fmt.Println(strconv.Itoa(n))
fmt.Println(string(n))
}
Output:
65
A
The program imports strconv because it uses strconv.Itoa. string(n) gave A, because computers store each letter as a number, and 65 is the number for A. Go compiles this line without a complaint, so the mistake is easy to miss.
The other way, strconv.Atoi turns a string into an int. The text might not be a number, so Atoi gives back two values: the number, and an error that says what went wrong:
n, err := strconv.Atoi("42")
fmt.Println(n+1, err)
bad, err := strconv.Atoi("12x")
fmt.Println(bad, err)
Output:
43 <nil>
0 strconv.Atoi: parsing "12x": invalid syntax
<nil> means "no error". For "12x", the number is 0 and the error explains the problem. The second := is allowed because bad is a new variable; err just gets a new value. The Multiple Return Values lesson explains functions that give back two values.
In the exercise, convert before dividing, so the average keeps its decimal part.