Back-end · formation gratuite

Go Training

Learn Go, Google's modern programming language

  • Intermédiaire
  • 12 chapitres
  • Exemples de code
  • 100 % gratuit
Commencer le cours

Introduction to Go

Go (also called Golang) is an open-source programming language developed by Google in 2009. Go combines Python's simplicity with C/C++ performance, and offers excellent concurrency management with goroutines.

🚀 What is Go?

Go is a compiled, statically typed, and concurrent programming language. Go was designed to be simple, efficient, and productive, with fast compilation and performant execution.

💡 Why is Go so popular?

  1. Performance - Fast compilation and performant execution, close to C/C++
  2. Simplicity - Clear and minimalist syntax, easy to learn
  3. Concurrency - Goroutines and channels for easy concurrent programming
  4. Google - Developed and maintained by Google, used by major companies
  5. Cross-platform - Compiles to a single binary for Windows, Linux, macOS
  6. Ecosystem - Rich standard library, built-in tools (go fmt, go test)

🚀 Why learn Go?

Go is an excellent choice for modern backend and microservices development:

  • ✅ Modern backend - Perfect for creating REST APIs, microservices, and cloud applications
  • ✅ Performance - Fast and memory-efficient applications
  • ✅ Concurrency - Goroutines to handle thousands of simultaneous connections
  • ✅ High demand - Used by Google, Docker, Kubernetes, Uber, Dropbox
  • ✅ Simple - Clear syntax, fast compilation, no complex dependencies
  • ✅ Cloud ecosystem - Ideal for cloud-native and DevOps development

📋 Prerequisites to learn Go

To learn Go effectively, it is recommended to have:

  • ✅ Programming basics - Understanding basic concepts (variables, conditions, loops)
  • ✅ Logic - Good understanding of programming logic

💡 Important note: To compile Go code, you need the Go SDK. Download it from go.dev. You can use VS Code with the Go extension, or GoLand (JetBrains IDE).

🎯 Go Use Cases

Go is used in many fields:

  • Backend & APIs - REST API development, microservices, backend services
  • Cloud & DevOps - Docker, Kubernetes, cloud-native tools
  • Distributed systems - Distributed applications, file systems
  • CLI tools - High-performance command-line tools
  • Networking - Network servers, proxies, load balancers

📝 Basic Syntax

Go syntax is simple and clear. Go uses braces {} to define code blocks and requires a semicolon ; (optional, added automatically).

// Premier programme Go
package main

import "fmt"

func main() {
    fmt.Println("Bonjour, monde !")

    nom := "NiangProgrammeur"
    age := 25
    fmt.Printf("Je m'appelle %s et j'ai %d ans\n", nom, age)
}

💡 Important points about Go syntax:

  • Go uses braces {} to define code blocks
  • Comments use // for a line or /* */ for multiple lines
  • Optional semicolon - Go automatically adds semicolons
  • Each Go file must belong to a package (package main for executables)
  • Main function - Entry point: func main()
  • Conventions - Use camelCase for variables, PascalCase for exports

🔍 Detailed syntax example

Here is a complete example showing several aspects of Go syntax:

// Définition d'une fonction
package main

import "fmt"

// saluer renvoie un message de bienvenue
func saluer(nom string) string {
    return "Bonjour, " + nom + " !"
}

func main() {
    message := saluer("Awa")
    fmt.Println(message) // Bonjour, Awa !
}

🔤 Variables

In Go, variables can be declared in several ways. Go is a statically typed language, meaning the type must be known at compile time.

package main

import "fmt"

func main() {
    // Déclaration avec le mot-clé var (type explicite)
    var nom string = "Go"
    var age int = 14

    // Déclaration courte : le type est déduit
    prix := 19.99
    estActif := true

    // Plusieurs variables à la fois
    var x, y, z = 1, 2, 3

    // Constantes : valeur fixée à la compilation
    const Pi = 3.14159

    // Valeur zéro : une variable non initialisée vaut 0, "" ou false
    var compteur int

    fmt.Println(nom, age, prix, estActif)
    fmt.Println(x, y, z, Pi, compteur)
}

📌 Rules for variable names:

  • Must start with a letter or underscore _
  • Can contain letters, numbers, and underscores
  • Case sensitive (age ≠ Age)
  • Cannot be Go keywords
  • Convention: use camelCase for variables

📊 Data Types

Go has several built-in data types. Here are the main ones:

package main

import "fmt"

func main() {
    // Types de base
    var entier int = 42
    var grand int64 = 9000000000
    var decimal float64 = 3.14
    var texte string = "Bonjour"
    var vrai bool = true
    var lettre rune = 'A'   // un caractère Unicode
    var octet byte = 255

    // Tableau (taille fixe) et slice (taille variable)
    notes := [3]int{12, 15, 18}
    langages := []string{"Go", "Python", "PHP"}
    langages = append(langages, "Rust")

    // Map (dictionnaire clé → valeur)
    ages := map[string]int{"Awa": 20, "Moussa": 22}

    fmt.Println(entier, grand, decimal, texte, vrai, lettre, octet)
    fmt.Println(notes, langages, len(langages), ages["Awa"])
    fmt.Printf("Type de decimal : %T\n", decimal) // float64
}

📚 Go Data Types:

  • string - Character strings
  • int, int8, int16, int32, int64 - Signed integers
  • uint, uint8, uint16, uint32, uint64 - Unsigned integers
  • float32, float64 - Decimal numbers
  • bool - Booleans (true/false)
  • byte - Alias for uint8
  • rune - Alias for int32 (Unicode character)

🔢 Operators

Go supports arithmetic, comparison, logical, and assignment operators:

package main

import "fmt"

func main() {
    a, b := 17, 5

    // Opérateurs arithmétiques
    fmt.Println(a + b)  // 22
    fmt.Println(a - b)  // 12
    fmt.Println(a * b)  // 85
    fmt.Println(a / b)  // 3 (division entière entre int)
    fmt.Println(a % b)  // 2 (reste)
    fmt.Println(float64(a) / float64(b)) // 3.4

    // Opérateurs de comparaison
    fmt.Println(a == b, a != b, a > b, a <= b) // false true true false

    // Opérateurs logiques
    majeur, inscrit := true, false
    fmt.Println(majeur && inscrit) // false
    fmt.Println(majeur || inscrit) // true
    fmt.Println(!majeur)           // false

    // Affectation combinée et incrémentation
    total := 10
    total += 5 // 15
    total *= 2 // 30
    total++    // 31 (++ est une instruction, pas une expression)
    fmt.Println(total)
}

🔀 Conditional Structures

Go uses if, else if, and else for conditions. Go also supports switch for multiple selections.

package main

import "fmt"

func main() {
    note := 14

    // if / else if / else (pas de parenthèses, accolades obligatoires)
    if note >= 16 {
        fmt.Println("Très bien")
    } else if note >= 10 {
        fmt.Println("Admis")
    } else {
        fmt.Println("Ajourné")
    }

    // if avec une déclaration courte : age n'existe que dans le bloc
    if age := 20; age >= 18 {
        fmt.Println("Majeur")
    }

    // switch : pas besoin de break
    jour := "samedi"
    switch jour {
    case "samedi", "dimanche":
        fmt.Println("Week-end")
    default:
        fmt.Println("Semaine")
    }

    // switch sans expression : remplace une suite de if
    switch {
    case note >= 16:
        fmt.Println("Mention très bien")
    case note >= 14:
        fmt.Println("Mention bien")
    }
}

🔄 Loops

Go offers a single loop: for, which can be used in different ways (as while, classic for, range):

package main

import "fmt"

func main() {
    // for classique (Go n'a qu'un mot-clé de boucle : for)
    for i := 1; i <= 5; i++ {
        fmt.Println("Tour", i)
    }

    // for utilisé comme while
    compteur := 3
    for compteur > 0 {
        fmt.Println("Compte à rebours :", compteur)
        compteur--
    }

    // range : parcourir une slice (index et valeur)
    langages := []string{"Go", "Python", "PHP"}
    for i, langage := range langages {
        fmt.Println(i, langage)
    }

    // range sur une map
    ages := map[string]int{"Awa": 20, "Moussa": 22}
    for nom, age := range ages {
        fmt.Println(nom, "a", age, "ans")
    }

    // break et continue
    for n := 1; n <= 10; n++ {
        if n%2 == 0 {
            continue // ignore les nombres pairs
        }
        if n > 7 {
            break // arrête la boucle
        }
        fmt.Println(n) // 1 3 5 7
    }
}

⚙️ Functions

Functions in Go are defined with func. Go supports functions with multiple return values, which is very useful for error handling.

package main

import (
    "errors"
    "fmt"
)

// Fonction simple avec paramètres et valeur de retour
func addition(a, b int) int {
    return a + b
}

// Plusieurs valeurs de retour : très courant en Go
func diviser(a, b float64) (float64, error) {
    if b == 0 {
        return 0, errors.New("division par zéro")
    }
    return a / b, nil
}

// Fonction variadique : nombre d'arguments variable
func somme(nombres ...int) int {
    total := 0
    for _, n := range nombres {
        total += n
    }
    return total
}

func main() {
    fmt.Println(addition(3, 4)) // 7

    resultat, err := diviser(10, 0)
    if err != nil {
        fmt.Println("Erreur :", err)
    } else {
        fmt.Println(resultat)
    }

    fmt.Println(somme(1, 2, 3, 4)) // 10

    // Fonction anonyme stockée dans une variable
    carre := func(x int) int { return x * x }
    fmt.Println(carre(5)) // 25
}

📋 Structs & Interfaces

Structs allow grouping data. Interfaces define contracts that types must respect.

package main

import "fmt"

// Struct : regroupe des données
type Etudiant struct {
    Nom   string
    Age   int
    Notes []float64
}

// Méthode attachée à la struct
func (e Etudiant) Moyenne() float64 {
    total := 0.0
    for _, n := range e.Notes {
        total += n
    }
    return total / float64(len(e.Notes))
}

// Interface : un contrat que les types doivent respecter
type Forme interface {
    Aire() float64
}

type Rectangle struct{ Largeur, Hauteur float64 }
type Cercle struct{ Rayon float64 }

func (r Rectangle) Aire() float64 { return r.Largeur * r.Hauteur }
func (c Cercle) Aire() float64    { return 3.14159 * c.Rayon * c.Rayon }

func main() {
    awa := Etudiant{Nom: "Awa", Age: 20, Notes: []float64{14, 16, 12}}
    fmt.Printf("%s : %.1f de moyenne\n", awa.Nom, awa.Moyenne()) // 14.0

    // Rectangle et Cercle respectent Forme sans le déclarer
    formes := []Forme{Rectangle{4, 3}, Cercle{2}}
    for _, f := range formes {
        fmt.Printf("Aire : %.2f\n", f.Aire())
    }
}

📦 Packages

Go organizes code into packages. Each Go file belongs to a package, and you can import packages with <code>import</code>.

// Fichier : mathutils/mathutils.go
package mathutils

// Une fonction qui commence par une majuscule est exportée (publique)
func Carre(x int) int {
    return x * x
}

// Une fonction en minuscule reste privée au package
func interne() {}

// Fichier : main.go
package main

import (
    "fmt"
    "math"     // package de la bibliothèque standard
    "strings"

    "monprojet/mathutils" // votre propre package
)

func main() {
    fmt.Println(math.Sqrt(16))              // 4
    fmt.Println(strings.ToUpper("dakar"))  // DAKAR
    fmt.Println(mathutils.Carre(7))         // 49
}

// Dans le terminal :
// go mod init monprojet        (crée le module)
// go get github.com/gin-gonic/gin  (ajoute une dépendance)
// go run .                     (exécute le programme)

🏗️ Goroutines & Channels

Go excels in concurrent programming with goroutines (lightweight threads) and channels (communication channels).

package main

import (
    "fmt"
    "sync"
    "time"
)

func telecharger(fichier string, wg *sync.WaitGroup) {
    defer wg.Done() // signale la fin de la tâche
    time.Sleep(100 * time.Millisecond)
    fmt.Println("Terminé :", fichier)
}

func main() {
    // Goroutines : lancer des tâches en parallèle avec le mot-clé go
    var wg sync.WaitGroup
    for _, f := range []string{"a.pdf", "b.pdf", "c.pdf"} {
        wg.Add(1)
        go telecharger(f, &wg)
    }
    wg.Wait() // attend la fin de toutes les goroutines

    // Channels : faire communiquer des goroutines
    resultats := make(chan int)
    go func() {
        for i := 1; i <= 3; i++ {
            resultats <- i * i // envoi dans le channel
        }
        close(resultats)
    }()
    for r := range resultats { // réception jusqu'à la fermeture
        fmt.Println("Reçu :", r) // 1, 4, 9
    }

    // select : attendre le premier channel prêt (ou un délai)
    ch := make(chan string)
    go func() { ch <- "réponse" }()
    select {
    case msg := <-ch:
        fmt.Println(msg)
    case <-time.After(time.Second):
        fmt.Println("Délai dépassé")
    }
}

📁 File Manipulation

Go allows reading and writing files easily with the os and io packages.

package main

import (
    "bufio"
    "fmt"
    "os"
)

func main() {
    // Écrire dans un fichier (créé ou écrasé)
    err := os.WriteFile("notes.txt", []byte("Awa : 15\nMoussa : 12\n"), 0644)
    if err != nil {
        fmt.Println("Erreur d'écriture :", err)
        return
    }

    // Ajouter du texte à la fin du fichier
    f, err := os.OpenFile("notes.txt", os.O_APPEND|os.O_WRONLY, 0644)
    if err == nil {
        f.WriteString("Fatou : 17\n")
        f.Close()
    }

    // Lire tout le fichier
    contenu, err := os.ReadFile("notes.txt")
    if err == nil {
        fmt.Print(string(contenu))
    }

    // Lire ligne par ligne
    fichier, err := os.Open("notes.txt")
    if err != nil {
        fmt.Println("Fichier introuvable")
        return
    }
    defer fichier.Close() // fermé automatiquement à la fin de main

    scanner := bufio.NewScanner(fichier)
    for scanner.Scan() {
        fmt.Println("Ligne :", scanner.Text())
    }
}

💡 Best practice: Use defer to close files automatically. This ensures the file will be closed even in case of an error.

🎓 Next Steps

Congratulations! You now have a solid foundation in Go.

✅ What you have learned:

  • Go syntax and variables
  • Data types (string, int, float, bool)
  • Operators and expressions
  • Conditional structures (if, else, switch)
  • Loops (for)
  • Functions and multiple return values
  • Structs and interfaces
  • Packages and imports
  • Goroutines and channels
  • File manipulation

🚀 To go further:

  • Advanced concurrency - Goroutines, channels, select
  • Interfaces - Polymorphism in Go
  • Packages - Creating and using packages
  • Web development - net/http to create HTTP servers
  • Databases - database/sql to interact with databases
Cliquer pour discuter avec NiangProgrammeur
NiangProgrammeur
En ligne

Bonjour ! 👋

Comment puis-je vous aider aujourd'hui ?