Converting Strings and Integers
We can use functions from the strconv
package to convert between strings and integers:
package main
import (
"fmt"
"strconv"
)
func main() {
// Declare a string a and an integer b
a, b := "233", 223
// Use Atoi to convert a string to an integer
c, _ := strconv.Atoi(a)
// Use Sprintf and Itoa functions respectively
// to convert an integer to a string
d1 := fmt.Sprintf("%d", b)
d2 := strconv.Itoa(b)
fmt.Printf("The type of a: %T\n", a) // string
fmt.Printf("The type of b: %T\n", b) // int
fmt.Printf("The type of c: %T\n", c) // int
fmt.Printf("The type of d1: %T\n", d1) // string
fmt.Printf("The type of d2: %T\n", d2) // string
}
go run string.go
The expected output is as follows:
The type of a: string
The type of b: int
The type of c: int
The type of d1: string
The type of d2: string
In the program, we use the Sprintf()
function from the fmt
package, which has the following format:
func Sprintf(format string, a ...interface{}) string
format
is a string with escape sequences, a
is a constant or variable that provides values for the escape sequences, and ...
means that there can be multiple variables of the same type as a
. The string after the function represents that Sprintf
returns a string. Here's an example of using this function:
a = fmt.Sprintf("%d+%d=%d", 1, 2, 3)
fmt.Println(a) // 1+2=3
In this code snippet, the format
is passed with three integer variables 1, 2, and 3. The %d
integer escape character in format
is replaced by the integer values, and the Sprintf
function returns the result after replacement, 1+2=3
.
Also, note that when using strconv.Atoi()
to convert a string to an integer, the function returns two values, the converted integer val
and the error code err
. Because in Go, if you declare a variable, you must use it, we can use an underscore _
to ignore the err
variable.
When strconv.Atoi()
converts correctly, err
returns nil
. When an error occurs during conversion, err
returns the error message, and the value of val
will be 0. You can change the value of string a
and replace the underscore with a normal variable to try it yourself.