Today we continue learning about Strings in Go and will find out how to parse data from strings.
In very simple terms, parsing data means that we take some raw data (in this case, we take it from a string), and then we put a specific meaning into the data (we convert it to its respective type).
In this topic, we'll learn how to parse data such as int, float64, and bool type values from string values or variables and then convert them to their respective types with the help of the strconv package.
Parsing integer numbers from strings
Suppose we have a string that contains integer numeric values; we can easily parse this data and convert it to an int type with the strconv.Atoi() function:
package main
import (
"fmt"
"log"
"strconv"
)
func main() {
num := "123" // 'num' contains a string of integer numbers
fmt.Printf("Initial type: %T | value: %v\n", num, num)
val, err := strconv.Atoi(num) // We save the converted value in the 'val' variable
if err != nil {
log.Fatal(err) // Exit if we have an error
}
fmt.Printf("Converted type: %T | value: %v", val, val)
}
// Output:
// Initial type: string | value: 123
// Converted type: int | value: 123
The strconv.Atoi() function returns two values: the result of the conversion to the int type, and an error if there is any. The Atoi acronym stands for "ASCII to integer", and it is a convenient function to convert base-10 integer numbers.
Another function that we can implement to convert strings to int types is the strconv.ParseInt() function. It takes as arguments the string that contains the integer value, the base of the number, and finally the bitSize:
...
func main() {
num := "123"
fmt.Printf("Initial type: %T | value: %v\n", num, num)
val, err := strconv.ParseInt(num, 10, 64)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Converted type: %T | value: %v", val, val)
}
// Output:
// Initial type: string | value: 123
// Converted type: int64 | value: 123
After passing the num variable to the strconv.ParseInt() function, we pass 10 as the base argument. This informs the function that we are working with base-10 integer values.
The last argument we pass is the bitSize; it specifies the integer type that the result must fit into. Bit sizes 0, 8, 16, 32, and 64 correspond to int, int8, int16, int32, and int64 values, respectively.
Atoi() function, if we were to express it using the ParseInt() function, would be: strconv.ParseInt(string, 10, 0), since Atoi() is a convenient function to convert base-10 integer values.Parsing float numbers from strings
We can also convert float numeric values with the strconv.ParseFloat() function:
...
func main() {
num := "3.1416" // 'num' contains a string of floating point numbers
fmt.Printf("Initial type: %T | value: %v\n", num, num)
val, err := strconv.ParseFloat(num, 64)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Converted type: %T | value: %v", val, val)
}
// Output:
// Initial type: string | value: 3.1416
// Converted type: float64 | value: 3.1416
The strconv.ParseFloat() function takes two arguments: the string that contains the float number and the bitSize — either 32 for float32 or 64 for float64 values.
Take notice that when the bitSize is 32, the returned conversion still has type float64; however, it will be convertible to float32 without changing its value.
Another important detail is that the strconv.ParseFloat() function recognizes the strings "NaN" (not a number), and the possibly signed strings "Inf" and "Infinity" as their respective special floating-point values:
...
func main() {
if val, err := strconv.ParseFloat("NaN", 32); err == nil {
fmt.Printf("Type: %T | value: %v\n", val, val)
}
if val, err := strconv.ParseFloat("Infinity", 32); err == nil {
fmt.Printf("Type: %T | value: %v\n", val, val)
}
}
// Output:
// Type: float64 | value: NaN
// Type: float64 | value: +InfConverting numeric values to strings
We've previously seen how to convert numeric values contained in strings to integer and float types. However, we can also perform inverse operations: converting int or float64 values to a string.
Let's take a look at converting an int to a string value first:
...
func main() {
num := 456 // 'num' contains an integer value
fmt.Printf("Initial type: %T | value: %v\n", num, num)
val := strconv.Itoa(num) // Converts 'num' to a string and assigns it to 'val'
fmt.Printf("Converted type: %T | value: %v", val, val)
}
// Output:
// Initial type: int | value: 456
// Converted type: string | value: 456
The strconv.Itoa() function is very simple: it takes an int type variable and simply returns the converted value as a string. The Itoa acronym stands for "Integer to ASCII".
Now let's see how to convert a float64 to a string value using the strconv.FormatFloat() function:
...
func main() {
num := 3.1415926535
fmt.Printf("Initial type: %T | value: %v\n", num, num)
val := strconv.FormatFloat(num, 'f', -1, 32)
fmt.Printf("Converted type: %T | value: %v\n\n", val, val)
fmt.Printf("Initial type: %T | value: %v\n", num, num)
val = strconv.FormatFloat(num, 'f', -1, 64)
fmt.Printf("Converted type: %T | value: %v", val, val)
}
// Output:
// Initial type: float64 | value: 3.1415926535
// Converted type: string | value: 3.1415927
// Initial type: float64 | value: 3.1415926535
// Converted type: string | value: 3.1415926535
The strconv.FormatFloat() is a bit more complex. It takes four arguments: the float64 type variable we want to convert, the formatting type, the precision control, and finally, the bitSize.
In the above example, we use the most basic formatting type: 'f' for no exponents. For the precision control, we use the special value -1 that uses the smallest number of digits necessary such that ParseFloat returns 'f' exactly.
strconv.FormatFloat() documentation.Parsing boolean values from strings
So far we've seen how to parse int and float64 values from strings. Now let's take a look at how to parse bool values contained in strings using the strconv.ParseBool() function.
The strconv.ParseBool() function takes a string containing a bool value as an argument and returns the boolean value represented by the string, as well as an error if there is any:
...
func main() {
b := "false"
fmt.Printf("Initial type: %T | value: %v\n", b, b)
val, err := strconv.ParseBool(b)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Converted type: %T | value: %v\n\n", val, val)
}
// Output:
// Initial type: string | value: false
// Converted type: bool | value: false
strconv.ParseBool() function is that it only accepts the following string values: 1, t, T, TRUE, true, True, 0, f, F, FALSE, false, False. Any other string value returns an error!We can also perform the inverse operation: converting a bool type to a string with the help of the strconv.FormatBool() function:
...
func main() {
b := false
fmt.Printf("Initial type: %T | value: %v\n", b, b)
val := strconv.FormatBool(b)
fmt.Printf("Converted type: %T | value: %v\n\n", val, val)
}
// Output:
// Initial type: bool | value: false
// Converted type: string | value: false
Take notice that the strconv.FormatBool() function only accepts boolean values. Therefore, we will only be able to pass either true or false values to it. Any other values we pass will cause an error.
Summary
In this topic, we've learned how to parse data from strings and convert it to their respective type with the help of the strconv package.
In particular, we've covered the following theory:
- How to parse
inttype values from strings with thestrconv.Atoi()and thestrconv.ParseInt()functions. - How to parse
float64type values from strings with thestrconv.ParseFloat()function. - How to parse a specific list of
booltype values from strings with thestrconv.ParseBool()function. - That we can also perform the inverse operation — convert
int,float64and evenbooltype values with thestrconv.Itoa(),strconv.FormatFloat()andstrconv.FormatBool()functions, respectively.
Congratulations that you've made it this far! Let's solve some theory and coding tasks now to make sure we've learned the most important details regarding parsing data from strings.