Go:Conversion de types en Go et paquet strconv (Atoi, Itoa)
Go•Conversion de types

Conversion de types en Go et paquet strconv (Atoi, Itoa)

Apprenez les conversions explicites de types en Go et l’analyse sûre de chaînes en nombres avec strconv.

Syntaxe

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

Paramètres et valeurs

Composants clés et valeurs acceptées pour cette structure :

ParamètreTypeDescription
strconv.AtoiFunctionConversion ASCII vers entier renvoyant (int, error).
strconv.ItoaFunctionConversion entier vers chaîne ASCII.

Exemple de code prêt à exécuter

Exécutable dans Compilra

Exécutez cet exemple complet directement sans installer Go localement :

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)
}
Sortie attendue :
Float to int: 42 (from 42.85)
Parsed port:  8080 (Port + 1 = 8081)

Fonctionnement étape par étape

  • Lignes 10-12: La conversion explicite int(floatVal) tronque la décimale.
  • Lignes 15-17: strconv.Atoi convertit une chaîne en int et renvoie la vérification d’erreur.

Concepts clés

  • En Go, toutes les conversions sont explicites : T(v).
  • strconv.Atoi renvoie à la fois l’entier analysé et un objet error.

Erreur fréquente : Utiliser string(int) en attendant la chaîne "65"

En Go, string(65) convertit l’entier en caractère ASCII "A", PAS en chaîne "65" !

❌ Incorrect
s := string(65) // Evaluates to "A", not "65"!
✅ Correct
s := strconv.Itoa(65) // Evaluates to "65"

Tutoriels Go associés et compilateur

Exécutez et testez Go sur Compilra

Exécutez cet extrait de code avec une entrée standard pré-fournie (stdin) dans le compilateur cloud de Compilra.

Go Compilateur en ligne