Golang: Converting Between Integers and Strings
Introduction
In Go programming language, one common task is to convert between various data types. In this article, we will focus on the conversions between integers and strings, specifically converting Golang int to string and Golang string to int. Converting between data types is essential as different types have different uses in various contexts.
Golang Int to String
To convert an integer to a string in Go, you can use the FormatInt function from the strconv package. FormatInt takes an int64 and a base as its arguments, then returns the string representation.
import "strconv"
func main() {
num := int64(42)
base := 10
str := strconv.FormatInt(num, base)
fmt.Println(str)
}
Golang String to Int
Converting a string to an integer in Go requires the use of the ParseInt function from the strconv package. ParseInt takes a string, a base, and a bit size, then returns the parsed int64.
import "strconv"
func main() {
str := "42"
base := 10
bitSize := 64
num, err := strconv.ParseInt(str, base, bitSize)
if err != nil {
fmt.Println(err)
} else {
fmt.Println(num)
}
}
Other Common Type Conversions
In addition to converting integers and strings, it may be useful to know about other common conversions in Golang. Here are some examples:
1. Float to String
You can use the FormatFloat function from the strconv package to convert a float to its string representation.
2. String to Float
To convert a string to a float64, use the ParseFloat function from the strconv package.
3. Rune to string
To convert a rune to a string, you can simply use the string keyword followed by the rune enclosed in parentheses, like this: str := string(rune).
Conclusion
In this article, we have looked into converting between integers and strings (Golang int to string and Golang string to int) using the strconv package. Additionally, we discussed other common type conversions in Go. Being familiar with these conversions will help you write efficient and clear code in Go.