Go:Go の型変換と strconv パッケージ (Atoi, Itoa)
Go•型変換

Go の型変換と strconv パッケージ (Atoi, Itoa)

Go における明示的な型変換と、strconv を使って安全に文字列を数値へ変換する方法を学びます。

構文

val := int(floatVal) num, err := strconv.Atoi("123")

パラメータと値

この構文の主な構成要素と指定可能な値:

パラメータ型説明
strconv.AtoiFunction(int, error) を返す ASCII から整数への変換。
strconv.ItoaFunction整数から ASCII 文字列への変換。

そのまま実行できるコード例

Compilra で実行可能

Go をローカルにインストールせずに、この動作する完全なコード例を直接実行できます:

package main

import (
    "fmt"
    "strconv"
)

func main() {
    // 1. Primitive conversion
    floatVal := 42.85
    intVal := int(floatVal) // Truncates decimal
    fmt.Printf("Float to int: %d (from %.2f)\n", intVal, floatVal)

    // 2. String to integer parsing with strconv.Atoi
    rawInput := "8080"
    port, err := strconv.Atoi(rawInput)
    if err != nil {
        fmt.Println("Parse Error:", err)
        return
    }
    fmt.Printf("Parsed port:  %d (Port + 1 = %d)\n", port, port+1)
}
期待される出力:
Float to int: 42 (from 42.85)
Parsed port:  8080 (Port + 1 = 8081)

動作のしくみ: ステップ解説

  • 10-12 行目: 明示的な int(floatVal) キャストが小数部を切り捨てます。
  • 15-17 行目: strconv.Atoi が文字列を int に変換しエラーチェックを返します。

重要ポイント

  • Go ではすべての変換が明示的です:T(v)。
  • strconv.Atoi は解析した整数と error オブジェクトの両方を返します。

よくある間違い: 文字列 "65" を期待して string(int) を使用する

Go では string(65) は整数を ASCII 文字 "A" に変換し、文字列 "65" にはなりません!

❌ 誤り
s := string(65) // Evaluates to "A", not "65"!
✅ 正しい例
s := strconv.Itoa(65) // Evaluates to "65"

関連するGoチュートリアルとコンパイラ

Compilra で Go を実行・テストする

Compilraのクラウドコンパイラ上で事前設定した標準入力 (stdin) を使ってこのコードを実行できます。

Go オンラインコンパイラ