How to Convert GoLang Integer to String Conversion

How to Convert GoLang Integer to String Conversion

Learn how to convert integers to strings and how to convert strings to integers in GoLang

1. Introduction

In this short tutorial, we'll learn how to convert a string to an integer and back again using Go. To complete this task, we will use the Strconv Package.

2. String to Integer Conversion

To convert a string to an integer, we'll use the Atoi function. This function takes in a string and returns an integer.

Code Example:

package main

import (
	"fmt"
	"strconv"
)

func main() {
	// Convert String to Integer
	num, err := StringToInteger("9876")

        // Check for error
	if err != nil {
		fmt.Println(err)
	}

        // Print num
	fmt.Println(num)
}


func StringToInteger(str string) (int64, error) {
        // Convert String to Integer 
	// This only works for int, int8, int16, and int64
	return strconv.Atoi(str)
}

Run Code

3. Integer to String Conversion

To convert an integer to a string, we'll use the Itoa function. This function takes in an integer and returns a string.

Code Example:

package main

import (
	"fmt"
	"strconv"
)

func main() {
	// Convert Integer to String
	str := IntegerToString(9876)

	// Print String
	fmt.Println(str)
}

func IntegerToString(number int64) string {
	// Convert Integer to String
	return strconv.Itoa(number)
}

Run Code

4. Conclusion

In this short tutorial, we'll learn how to convert a string to an integer and back again.

Did you like it? Why don't you try also...

How to remove the first character of a string in Golang

How to remove the first character of a string in Golang

Learn how to remove first the character of a string in GoLang

Go Strings Cheat Sheet Part 1

Go Strings Cheat Sheet Part 1

Learn the Basic of Working with GoLang Strings.

Is String a Palindrome?

Is String a Palindrome?

Learn How to Test if a String is a Palindrome in Go.