strconv
Things in Go have types. And when required, we can convert between types with built-in casts or more complex custom methods.
In most languages, casting involves a series of complex considerations. It often causes errors. Go here is no exception. Some casts are incompatible.
float
, int
This program casts a float
constant to an int
. We call the int
cast like a method. We can assign its result to an int
variable.
float
of value 1.2. When cast to an int
, we are left with 1—the numbers after the decimal place are dropped.package main
import "fmt"
func main() {
size := 1.2
fmt.Println(size)
// Convert to an int with a cast.
i := int(size)
fmt.Println(i)
}1.2
1
string
, intsWe cannot just cast ints to strings (or strings to ints). We must use methods in the strconv
module. We can use ParseInt
, FormatInt
, or the convenient Itoa
and Atoi
.
Itoa
and Atoi
methods are typically clearer.package main
import (
"fmt"
"strconv"
)
func main() {
value := 120
// Use Itoa to convert int to string.
result := strconv.Itoa(value)
fmt.Println(result)
if result == "120" {
fmt.Println(true)
}
// Use Atoi to convert string to int.
original, _ := strconv.Atoi(result)
if original == 120 {
fmt.Println(true)
}
}120
true
true
string
Here we convert a slice of strings into a single string
. We use the strings.Join
method. A comma character is inserted between all strings in the output.
package main
import (
"fmt"
"strings"
)
func main() {
// Slice of 3 strings.
values := []string{"fish", "chicken", "lettuce"}
// Convert slice into a string.
result := strings.Join(values, ",");
fmt.Println(result)
}fish,chicken,lettuce
String
, rune
sliceCharacters in a string
are called runes—these are like ints. We can convert a string
into a slice of runes. We also convert a rune
slice into a string
.
package main
import "fmt"
func main() {
// An example string.
value := "cat"
fmt.Println(value)
// Convert string into a slice of runes.
slice := []rune(value)
fmt.Println(slice)
// Convert rune slice into a string.
original := string(slice)
fmt.Println(original)
}cat
[99 97 116]
cat
More complex types (like map) can be converted also. We can use methods like append()
to build up slices from the parts of a map.
Conversions are a recurring problem in programs. With types, we gain reliability. But often, to call methods, we must convert variables into compatible ones.