Number Parsing in Go
Go: Number Parsing
Go's
strconv
package provides functionality for converting strings to numbers of various types. The package includes functions for parsing integers, floats, and booleans.
How to parse an integer from a string in Go
Here's an example of how to parse an integer from a string:
package main
import (
"fmt"
"strconv"
)
func main() {
str := "42"
num, err := strconv.Atoi(str)
if err != nil {
fmt.Println("Failed to parse integer:", err)
return
}
fmt.Println(num) // Output: 42
}
In this example, the strconv.Atoi()
function is used to parse the string "42" as an integer. The function returns two values: the parsed integer and an error. If the string cannot be parsed as an integer, the function returns an error.
Here are some other functions we can use to parse numbers in Go:
strconv.ParseInt(s string, base int, bitSize int) (int64, error)
: parses a string as a signed integer with the specified base (2 to 36) and bit size (0, 8, 16, 32, or 64).strconv.ParseUint(s string, base int, bitSize int) (uint64, error)
: parses a string as an unsigned integer with the specified base (2 to 36) and bit size (0, 8, 16, 32, or 64).strconv.ParseFloat(s string, bitSize int) (float64, error)
: parses a string as a float with the specified bit size (32 or 64).strconv.ParseBool(s string) (bool, error)
: parses a string as a boolean value (true
orfalse
).
Note that if the string cannot be parsed as the specified type, the parsing functions return an error. You should always check for errors when parsing numbers from strings to avoid unexpected behavior in your program.
Previous Article
Next Article
Golang Tutorials
- Hello World
- Operators in Go
- Declarations in Go
- Values in Go
- Variables in Go
- For in Go
- If/Else in Go
- Switch in Go
- Arrays in Go
- Slices in Go
- Maps in Go
- Range in Go
- Functions in Go
- Closures in Go
- Recursion in Go
- Pointers in Go
- Strings and Runes in Go
- Structs in Go
- Methods in Go
- Interfaces in Go
- Generics in Go
- Errors in Go
- Goroutines in Go
- Channels in Go
- Select in Go
- Timeouts in Go
- Timers in Go
- Worker Pools in Go
- WaitGroups in Go
- Mutexes in Go
- Sorting in Go
- Panic in Go
- Defer in Go
- Recover in Go
- JSON in Go
- XML in Go
- Time in Go
- Epoch in Go
- Time Formatting in Go
- Random Numbers in Go
- Number Parsing in Go
- URL Parsing in Go
- SHA256 Hashes in Go
- Base64 Encoding in Go
- Reading Files in Go
- Writing Files in Go
- File Paths in Go
- Directories in Go
- Testing and Benchmarking in Go
- Command-Line Arguments in Go
- Command-Line Flags in Go
- Command-Line Subcommands in Go
- Environment Variables in Go
- HTTP Client in Go
- HTTP Server in Go
- Context in Go
- Signals in Go