Convert int to string in Go: Simple method

If you're working with Go and need to convert an int to a string, there's a simple method you can use. The strconv package provides the necessary functions to convert between different data types, including int and string.

To convert an int to a string, you can use the strconv.Itoa() function. This function takes an int as a parameter and returns the corresponding string representation. Here's an example:

package main

import (
    "fmt"
    "strconv"
)

func main() {
    i := 42
    str := strconv.Itoa(i)
    fmt.Println(str)
}

In this example, we declare an int variable i with a value of 42. We then use the strconv.Itoa() function to convert i to a string and assign the result to a variable named str. Finally, we print the value of str to the console.

You can also use a similar method to convert a string to an int using the strconv.Atoi() function. This function takes a string as a parameter and returns the corresponding int value. Here's an example:

package main

import (
    "fmt"
    "strconv"
)

func main() {
    str := "42"
    i, err := strconv.Atoi(str)
    if err != nil {
        fmt.Println(err)
    }
    fmt.Println(i)
}

In this example, we declare a string variable str with a value of "42". We then use the strconv.Atoi() function to convert str to an int and assign the result to a variable named i. We also check for any errors that may occur during the conversion process using the err variable. Finally, we print the value of i to the console.

By using the strconv package in Go, you can easily convert between different data types, including int and string, using simple and efficient methods.

Click to rate this post!
[Total: 0 Average: 0]

Related posts

Leave a Reply

Your email address will not be published. Required fields are marked *

Go up

Below we inform you of the use we make of the data we collect while browsing our pages. You can change your preferences at any time by accessing the link to the Privacy Area that you will find at the bottom of our main page. More Information