G
Fonctions
Go Syntax Guide
Définir et appeler des fonctions en Go
Fonctions
Définir et appeler des fonctions en Go
Go fonctions (go)
package main
import "fmt"
// Function with parameters and return value
func add(a, b int) int {
return a + b
}
// Function with multiple return values
func divide(a, b float64) (float64, error) {
if b == 0 {
return 0, fmt.Errorf("division by zero")
}
return a / b, nil
}
// Variadic function
func sum(numbers ...int) int {
total := 0
for _, num := range numbers {
total += num
}
return total
}
// Anonymous function
func counter() func() int {
count := 0
return func() int {
count++
return count
}
}
// Struct definition
type Person struct {
Name string
Age int
}
// Method (function attached to a type)
func (p Person) Greet() string {
return fmt.Sprintf("Hello, I'm %s", p.Name)
}
// Pointer receiver method (can modify the struct)
func (p *Person) Birthday() {
p.Age++
}
// Interface definition
type Speaker interface {
Speak() string
}
// Implement interface
func (p Person) Speak() string {
return fmt.Sprintf("My name is %s and I'm %d years old", p.Name, p.Age)
}
// Function that accepts interface
func introduce(s Speaker) {
fmt.Println(s.Speak())
}
// Generic function (Go 1.18+)
func printSlice[T any](slice []T) {
for _, item := range slice {
fmt.Printf("%v ", item)
}
fmt.Println()
}
// Main function demonstrating usage
func main() {
// Basic function calls
result := add(5, 3)
fmt.Printf("5 + 3 = %d\n", result)
// Multiple return values
quotient, err := divide(10, 2)
if err != nil {
fmt.Println("Error:", err)
} else {
fmt.Printf("10 / 2 = %.2f\n", quotient)
}
// Variadic function
total := sum(1, 2, 3, 4, 5)
fmt.Printf("Sum: %d\n", total)
// Closure
increment := counter()
fmt.Println(increment()) // 1
fmt.Println(increment()) // 2
// Methods
person := Person{Name: "John", Age: 25}
fmt.Println(person.Greet())
person.Birthday()
fmt.Printf("After birthday: %d years old\n", person.Age)
// Interface
introduce(person)
// Generics
numbers := []int{1, 2, 3, 4, 5}
names := []string{"Alice", "Bob", "Charlie"}
printSlice(numbers)
printSlice(names)
}
Explanation
Les fonctions en Go sont déclarées avec le mot-clé func et peuvent retourner plusieurs valeurs, ce qui est un modèle commun pour la gestion des erreurs.
Common Use Cases
- Réutilisation du code
- Modularité
- Implémenter des blocs logiques spécifiques
Related Go Syntax
Master Fonctions in Go
Understanding Fonctions is fundamental to writing clean and efficient Go code. This comprehensive guide provides you with practical examples and detailed explanations to help you master this important concept.
Whether you're a beginner learning the basics or an experienced developer looking to refresh your knowledge, our examples cover real-world scenarios and best practices for using Fonctions effectively in your Go projects.
Key Takeaways
- Réutilisation du code
- Modularité
- Implémenter des blocs logiques spécifiques