How to Convert String to Int64 in Golang

1. Introduction

In Go, an int64 is a 64-bit signed integer. The strconv package's ParseInt function is used to convert a string to an int64. It parses a string as a specific base (like 10 for decimal), and bit size (64 for int64), and returns the corresponding integer value.

2. Program Steps

1. Import the strconv package.

2. Use the strconv.ParseInt function to convert a string to int64.

3. Handle any potential errors that arise from the conversion.

4. Print the result to verify the successful conversion.

3. Code Program

package main

import (
	"fmt"
	"strconv"
)

func main() {
	// Example string that represents an integer
	strNumber := "1234567890"

	// Step 2: Use strconv.ParseInt to convert string to int64
	intNumber, err := strconv.ParseInt(strNumber, 10, 64)
	if err != nil {
		// Step 3: Handle conversion error
		fmt.Println("Conversion error:", err)
	} else {
		fmt.Printf("Converted integer (int64): %d\n", intNumber)
	}
}

Output:

Converted integer (int64): 1234567890

Explanation:

1. package main - The package declaration for the Go program.

2. import "fmt" and import "strconv" - Import statements for the Format package and the string conversion package.

3. strNumber is a string that holds a number in base-10 format.

4. strconv.ParseInt is used to attempt to convert strNumber to an int64. It takes the string to convert, the base of the number (10 for decimal), and the bit size of the desired integer type (64 for int64).

5. The function returns two values: the converted int64 number and an error value. If an error occurs during conversion, it is printed to the console; otherwise, the successfully converted integer is printed.

6. The output shows the successfully converted string as an int64 integer.


Comments