📘

[Go] 数値↔文字列 を変換する

に公開

概要

Go言語での、数値と文字列の変換を行う方法についてのメモです。
いちど躓いたので書きました。

TL;DR

strconv パッケージを使用します。
https://pkg.go.dev/github.com/shogo82148/std/strconv

文字列→数値

strconv.Atoi を使用します。変換後の数値、エラーが返されます。

// success
i1, err := strconv.Atoi("123")
if err != nil {
  fmt.Println(err)
}

// failure
i2, err := strconv.Atoi("hoge")
if err != nil {
  fmt.Println(err)   // strconv.Atoi: parsing "hoge": invalid syntax
}

fmt.Println(i1, i2)   // 123 0

数値→文字列

strconv.Itoa を使用します。こちらは変換された文字列のみ返されます。

s := strconv.Itoa(123)
fmt.Println(s)   // 123

注意点として、string による変換は 数値に対応するコードポイントの文字 が返されます。
コンパイルエラーに引っかからないので注意。

s := string(123)
fmt.Println(s)   // {
GitHubで編集を提案
Progate Path コミュニティ

Discussion