この記事では、Go言語で文字列を数値(int, int64)に変換する方法を紹介します。
文字列をintに変換する
Goで文字列をintに変換するには、strconv.Atoi()を使用します。
strconv.Atoi()の実行例を次に示します。
package main
import (
"fmt"
"reflect"
"strconv"
)
func main() {
str := "123456"
num, _ := strconv.Atoi(str)
fmt.Println(reflect.TypeOf(num), num)
// int 123456
}
strconv.Atoi()を呼び出すときは、引数にintへの対象の文字列を渡します。
strconv package - strconv - Go Packages
Package strconv implements conversions to and from string representations of basic data types.
文字列をint64に変換する
Goでは、strconv.ParseInt()を使用することで文字列をint64に変換できます。
strconv.ParseInt()の実行例は次のとおりです。
package main
import (
"fmt"
"reflect"
"strconv"
)
func main() {
str := "123456"
num, _ := strconv.ParseInt(str, 10, 64)
fmt.Println(reflect.TypeOf(num), num)
// int64 123456
}
strconv.ParseInt()の第一引数には、変換対象の文字列を設定します。第二引数では、基数を10進数とするために、10を渡します。そして第三引数に、ビットサイズを指定します。
strconv package - strconv - Go Packages
Package strconv implements conversions to and from string representations of basic data types.