Yabu.log

ITなどの雑記

go言語で数値-文字変換を行う方法

基本的にプログラミングをするときは全部Javaだと思って書いているので、他言語の挙動に困惑することがよくあります。 Go言語では文字と数値を+演算子で連結した時に、数値が文字コードとして解釈されているような変換がされたので、 数値を文字に変換する方法を調べました。

実行環境

jshell

$ jshell -v
|  JShellへようこそ -- バージョン9.0.1

go

$ go version
go version go1.11 darwin/amd64

謝った文字列変換

fmt.Println("test" + 65)
//出力結果:testA

この通り65がAに変換されました。

※おそらく内部でstring(65)が実行されているものと思われます

JavaだとStringとint型を+で連結すると文字型に型変換された65が連結に利用されています。

jshell> String a = "test" + 65
a ==> "test65"

strconv.Itoaを使う

fmt.Println("test" + strconv.Itoa(65))
//出力結果:test65

内部ではFormatIntを呼び出しているようです。

// FormatInt returns the string representation of i in the given base,
// for 2 <= base <= 36. The result uses the lower-case letters 'a' to 'z'
// for digit values >= 10.
func FormatInt(i int64, base int) string {
    if fastSmalls && 0 <= i && i < nSmalls && base == 10 {
        return small(int(i))
    }
    _, s := formatBits(nil, uint64(i), base, i < 0, false)
    return s
}

// Itoa is shorthand for FormatInt(int64(i), 10).
func Itoa(i int) string {
    return FormatInt(int64(i), 10)
}

FormatIntをそのまま利用しても結果は同じになります。

fmt.Println("test" + strconv.FormatInt(int64(65), 10))
//出力結果:test65

参考

https://stackoverflow.com/questions/10105935/how-to-convert-an-int-value-to-string-in-go

https://golang.org/src/strconv/itoa.go?s=783:806#L14