📜  golang string to int (1)

📅  最后修改于: 2023-12-03 15:31:01.098000             🧑  作者: Mango

Golang String to Int

In Golang, we often need to convert a string to an integer. There are different ways to accomplish this task. In this article, we will explore the different methods available to convert a string to an int in Golang, with examples.

Using the strconv.ParseInt Function

The strconv package in Golang provides a ParseInt function that can be used to convert a string to an int. The function takes three arguments: the string to convert, the base, and the bit size of the result type. Here is an example:

package main

import (
    "fmt"
    "strconv"
)

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

Output:

42

In the above example, we first define a string str with the value "42". We then use the strconv.ParseInt function to convert the string to an int. The 10 in the second argument specifies the base (decimal), and 64 in the third argument specifies the bit size of the result type. The function returns two values: the converted int and an error. We use the if err != nil statement to check if the function returned an error.

Using the strconv.Atoi Function

Another way to convert a string to an int in Golang is to use the strconv.Atoi function. This function is simpler than the strconv.ParseInt function, as it assumes that the base is 10, and the bit size is 32. Here is an example:

package main

import (
    "fmt"
    "strconv"
)

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

Output:

42

In the above example, we define the same string str with the value "42". We then use the strconv.Atoi function to convert the string to an int. The function returns two values: the converted int and an error. We use the if err != nil statement to check if the function returned an error.

Conclusion

In this article, we explored the different methods available to convert a string to an int in Golang. We looked at the strconv.ParseInt function and the strconv.Atoi function, with examples. Depending on your use case, you can choose the method that best suits your needs.