Type Conversion
Prerequisites: Constants & iota
Go never converts between types automatically — not even from
int to float64. Every conversion is written out.
Syntax
f := float64(n) // Type(value) converts between numeric types
i := int(f) // truncates toward zero
Converting between numbers and text is different: it uses the
strconv ("string conversion") package.
strconv.Itoa(n)—inttostring("integer to ASCII").strconv.Atoi(s)—stringtoint. Because the text might not be a number, it returns two values: the number and anerror(which isnilwhen everything worked).
Example
package main
import (
"fmt"
"strconv"
)
func main() {
count := 7
total := 2
average := float64(count) / float64(total)
fmt.Println(average)
price := 19.99
fmt.Println(int(price))
label := "Item " + strconv.Itoa(42)
fmt.Println(label)
n, err := strconv.Atoi("123")
fmt.Println(n+1, err)
bad, err := strconv.Atoi("abc")
fmt.Println(bad, err)
}
Expected output
3.5
19
Item 42
124 <nil>
0 strconv.Atoi: parsing "abc": invalid syntax
<nil> means "no error". You'll learn to check errors properly
with if err != nil in the Multiple Return Values & Errors
lesson.
Common mistakes
- Writing
count / totalwith twoints and expecting3.5— integer division gives3. Convert before dividing. - Using
string(65)to turn a number into text. That produces"A"(the character with code 65), not"65"; usestrconv.Itoainstead.go vetwarns about this mistake. - Ignoring the error from
strconv.Atoi— on invalid input the number is silently0.
Practice
Convert the string "25" to an int, add 5, and print the
result along with the error value.
Show solution
package main
import (
"fmt"
"strconv"
)
func main() {
n, err := strconv.Atoi("25")
fmt.Println(n+5, err) // 30 <nil>
}