📄

intからstringにキャストするとgo testで怒られる

2022/09/11に公開

intからstringにキャストするとgo testで怒られる

再現方法

このようなコードを書いて

func TestStringCast(t *testing.T) {
	v := string(65)
	log.Print(v)
}

go test すると

conversion from untyped int to string yields a string of one rune, not a string of digits (did you mean fmt.Sprint(x)?)

というエラーが出る。

解消方法

v := string(65)v := string(rune(65)) とすると解消できる。

考察

このようなエラーが出る理由は、intな65をstringな"65"と変換したいのにUTF-8のコードポイントと解釈されてAと表示されるのを気づかせたかったのだと思うが、言語仕様なのでErrorではなくWarningのほうがいいのではないか…と思った。

GitHubで編集を提案

Discussion