Monday, January 20, 2025
HomeProgrammingConvert String To Integer Type In Go?

Convert String To Integer Type In Go?

To convert a string to an integer in Go, you can use the strconv package, which provides various utility functions for string conversions. The function commonly used for this purpose is strconv.Atoi or strconv.ParseInt.

Here’s how you can do it:

1. Using strconv.Atoi

strconv.Atoi converts a string to an int.

package main

import (
	"fmt"
	"strconv"
)

func main() {
	str := "123"
	num, err := strconv.Atoi(str)
	if err != nil {
		fmt.Println("Error:", err)
		return
	}
	fmt.Println("Converted integer:", num)
}
  • Input: A string representing an integer, like "123".
  • Output: An int type if the conversion is successful, or an error if the string cannot be converted.
See also  What Is Oracle MINUS operator?

2. Using strconv.ParseInt

strconv.ParseInt is more flexible and allows you to specify the base and the bit size for the integer.

package main

import (
	"fmt"
	"strconv"
)

func main() {
	str := "123"
	num, err := strconv.ParseInt(str, 10, 64) // Base 10, 64-bit integer
	if err != nil {
		fmt.Println("Error:", err)
		return
	}
	fmt.Println("Converted integer:", num)
}
  • Arguments:
    • str: The string to convert.
    • base: The numeric base (e.g., 10 for decimal, 16 for hexadecimal).
    • bitSize: The size of the integer (e.g., 0, 8, 16, 32, or 64).
  • Returns: A 64-bit integer (int64) and an error.
See also  What is Deletion in Binary Search Tree (BST)

To convert it to a specific integer type:

intNum := int(num) // Convert int64 to int if needed

Handling Conversion Errors

Always check for errors during conversion to handle cases where the string does not represent a valid integer.

Example:

str := "abc"
num, err := strconv.Atoi(str)
if err != nil {
    fmt.Println("Error:", err) // Will print: "Error: strconv.Atoi: parsing "abc": invalid syntax"
} else {
    fmt.Println("Converted integer:", num)
}

Choosing Between Atoi and ParseInt

  • Use strconv.Atoi if you are working specifically with base 10 and the default int type.
  • Use strconv.ParseInt if you need:
    • Support for bases other than 10 (e.g., binary, octal, hexadecimal).
    • Control over the bit size of the output integer.
RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x