Go strconv Package

beginner
15 min

Go strconv Package

Welcome to our deep dive into the strconv package in Go! This package is all about converting strings to other types and vice versa. Let's get started! 🚀

What is strconv? 📝

strconv is a standard Go package for converting strings to other types and back. It's an essential tool for working with user input or data that comes in string format.

Basic Usage 🎯

Before we dive into the specific functions, let's see a simple example of how to use strconv.

go
package main import ( "fmt" "strconv" ) func main() { numStr := "42" num, _ := strconv.Atoi(numStr) fmt.Println(num) // Output: 42 }

In this example, we're converting a string numStr containing the number 42 into an integer using strconv.Atoi(). The function returns a pair of values: the converted value and an error. In this case, we're ignoring the error for simplicity.

Key Functions 💡

Here are some of the most important functions in the strconv package:

strconv.Atoi(s string) (int, error)

Converts a string to an integer.

strconv.ParseFloat(s string, bitSize int) (float64, error)

Converts a string to a float64. The bitSize parameter specifies the bit size of the floating-point number. Use 64 for a double-precision float (default).

strconv.ParseInt(s string, base int, bitSize int) (int64, error)

Converts a string to an int64. The base parameter specifies the base of the number system (2-36). If bitSize is not provided, it's assumed to be 64.

strconv.FormatInt(i int64, base int, flag int) string

Converts an int64 to a string. The base parameter specifies the base of the number system (2-36). The flag parameter controls the formatting.

strconv.FormatFloat(f float64, format Runewidth, precision int, bitSize int) string

Converts a float64 to a string. The format parameter specifies the format (e.g., e, f, or g). The precision parameter specifies the number of digits after the decimal point. The bitSize parameter is the bit size of the floating-point number (64 for default).

Practical Example 📝

Let's create a simple command-line application that reads user input, converts it to a float, and prints the result.

go
package main import ( "bufio" "fmt" "os" "strconv" ) func main() { reader := bufio.NewReader(os.Stdin) fmt.Println("Enter a number:") text, _ := reader.ReadString('\n') num, _ := strconv.ParseFloat(text, 64) fmt.Printf("You entered %.2f\n", num) }

In this example, we're reading user input from the command line, converting it to a float, and printing the result.

Quiz Time! 🎯

Quick Quiz
Question 1 of 1

What function converts a string to an integer in Go?

That's it for our introduction to the strconv package in Go! Remember to practice using these functions to convert strings to other types and back. Happy coding! 🤖💻