Elysia Tools
Navigation mobile
Programming Languages
Exemples Go
Exemples de code Go (Golang) et démonstrations Hello World
Exemples
Entrées de cette collection
Go Hello World
Programme Hello World et exemples de syntaxe de base
Difficulté
3/10
Temps estimé
15 min
Étiquettes
go, golang, programming, concurrency
Prérequis
Basic programming concepts
// Go Hello World Examples
package main
import (
"fmt"
"strings"
"strconv"
"time"
)
// 1. Basic Hello World
func basicHelloWorld() {
fmt.Println("Hello, World!")
}
// 2. Hello World with variables
func helloWithVariables() {
message := "Hello, World!"
fmt.Println(message)
name := "Go"
greeting := "Hello, " + name + "!"
fmt.Println(greeting)
}
// 3. Hello World with function
func sayHello() string {
return "Hello, World!"
}
func greetWithName(name string) string {
return "Hello, " + name + "!"
}
// 4. Hello World with multiple returns
func getGreetingDetails() (string, string, int) {
return "Hello", "World", 2024
}
// 5. Hello World with struct
type Greeter struct {
Name string
Message string
}
func (g Greeter) Greet() string {
return g.Message + ", " + g.Name + "!"
}
func NewGreeter(name string) *Greeter {
return &Greeter{
Name: name,
Message: "Hello",
}
}
// 6. Hello World with interface
type Speaker interface {
Speak() string
}
type Person struct {
Name string
}
func (p Person) Speak() string {
return "Hello, my name is " + p.Name
}
// 7. Hello World with goroutine and channel
func helloAsync() {
ch := make(chan string)
go func() {
time.Sleep(100 * time.Millisecond)
ch <- "Hello from goroutine!"
}()
message := <-ch
fmt.Println(message)
}
// 8. Hello World with error handling
func safeGreet(name string) (string, error) {
if name == "" {
return "", fmt.Errorf("name cannot be empty")
}
return "Hello, " + name + "!", nil
}
// 9. Hello World with slice operations
func helloWithSlice() {
greetings := []string{"Hello", "Hola", "Bonjour", "こんにちは"}
for i, greeting := range greetings {
fmt.Printf("%d: %s, World!\n", i, greeting)
}
// Using strings.Builder
var builder strings.Builder
for _, greeting := range greetings {
builder.WriteString(greeting)
builder.WriteString(" ")
}
fmt.Println("All greetings:", builder.String())
}
// 10. Hello World with map
func helloWithMap() {
greetings := map[string]string{
"en": "Hello",
"es": "Hola",
"fr": "Bonjour",
"de": "Hallo",
"ja": "こんにちは",
}
for lang, greeting := range greetings {
fmt.Printf("%s: %s, World!\n", lang, greeting)
}
}
// Basic data types examples
func basicTypes() {
// Integer types
var integer int = 42
var int8Val int8 = 127
var int16Val int16 = 32767
var int32Val int32 = 2147483647
var int64Val int64 = 9223372036854775807
// Unsigned integers
var uintVal uint = 42
var uint8Val uint8 = 255
var uint16Val uint16 = 65535
var uint32Val uint32 = 4294967295
var uint64Val uint64 = 18446744073709551615
// Floating point
var float32Val float32 = 3.14
var float64Val float64 = 3.14159265359
// String
var text string = "Go"
// Boolean
var isActive bool = true
// Complex numbers
var complex64Val complex64 = 3 + 4i
var complex128Val complex128 = 3.14159 + 2.71828i
fmt.Printf("Integer: %d, Type: %T\n", integer, integer)
fmt.Printf("Float64: %f, Type: %T\n", float64Val, float64Val)
fmt.Printf("String: %s, Type: %T\n", text, text)
fmt.Printf("Boolean: %t, Type: %T\n", isActive, isActive)
fmt.Printf("Complex128: %v, Type: %T\n", complex128Val, complex128Val)
}
// Control flow examples
func controlFlow() {
// If-else
age := 18
if age >= 18 {
fmt.Println("You are an adult")
} else {
fmt.Println("You are a minor")
}
// Switch
day := "Monday"
switch day {
case "Monday":
fmt.Println("Start of the week")
case "Friday":
fmt.Println("End of the week")
default:
fmt.Println("Midweek")
}
// For loop (basic)
for i := 0; i < 5; i++ {
fmt.Printf("Iteration: %d\n", i)
}
// For loop (range over slice)
fruits := []string{"apple", "banana", "cherry"}
for index, fruit := range fruits {
fmt.Printf("%d: %s\n", index, fruit)
}
// For loop (while-like)
count := 0
for count < 3 {
fmt.Printf("Count: %d\n", count)
count++
}
}
// Function examples
func add(a int, b int) int {
return a + b
}
func swap(a, b string) (string, string) {
return b, a
}
func variadicSum(numbers ...int) int {
total := 0
for _, num := range numbers {
total += num
}
return total
}
// Main function demonstrating all examples
func main() {
fmt.Println("=== Go Hello World Examples ===")
// Basic hello world
fmt.Println("1. Basic Hello World:")
fmt.Println("Hello, World!")
// Variables
fmt.Println("\n2. Hello with variables:")
helloWithVariables()
// Functions
fmt.Println("\n3. Hello with functions:")
fmt.Println(sayHello())
fmt.Println(greetWithName("Go"))
// Multiple returns
fmt.Println("\n4. Multiple returns:")
greeting, target, year := getGreetingDetails()
fmt.Printf("%s, %s! (%d)\n", greeting, target, year)
// Structs
fmt.Println("\n5. Hello with struct:")
greeter := NewGreeter("Go")
fmt.Println(greeter.Greet())
// Interfaces
fmt.Println("\n6. Hello with interface:")
person := Person{Name: "Alice"}
fmt.Println(person.Speak())
// Goroutine (commented out as it would run async)
fmt.Println("\n7. Hello with goroutine:")
fmt.Println("(Goroutine example would run asynchronously)")
// Error handling
fmt.Println("\n8. Hello with error handling:")
if greeting, err := safeGreet("World"); err != nil {
fmt.Printf("Error: %v\n", err)
} else {
fmt.Println(greeting)
}
// Slices
fmt.Println("\n9. Hello with slice:")
helloWithSlice()
// Maps
fmt.Println("\n10. Hello with map:")
helloWithMap()
// Basic types
fmt.Println("\n=== Basic Types ===")
basicTypes()
// Control flow
fmt.Println("\n=== Control Flow ===")
controlFlow()
// Function examples
fmt.Println("\n=== Function Examples ===")
fmt.Printf("5 + 3 = %d\n", add(5, 3))
a, b := swap("hello", "world")
fmt.Printf("Swapped: %s, %s\n", a, b)
fmt.Printf("Sum of 1,2,3,4,5: %d\n", variadicSum(1, 2, 3, 4, 5))
// Type conversion
fmt.Println("\n=== Type Conversion ===")
str := "123"
num, err := strconv.Atoi(str)
if err != nil {
fmt.Printf("Error converting: %v\n", err)
} else {
fmt.Printf("String '%s' to int: %d\n", str, num)
}
fmt.Printf("Int to string: %s\n", strconv.Itoa(456))
}Patrons de Concurrence Go
Patrons avancés de concurrence Go avec goroutines, canaux et primitives de synchronisation
Difficulté
8/10
Temps estimé
30 min
Étiquettes
go, golang, concurrency, patterns
Prérequis
Basic Go syntax
// Go Concurrency Patterns Examples
package main
import (
"fmt"
"sync"
"time"
"context"
)
// 1. Basic Goroutine and Channel
func basicGoroutine() {
ch := make(chan string)
go func() {
time.Sleep(100 * time.Millisecond)
ch <- "Hello from goroutine!"
}()
message := <-ch
fmt.Println("1. Basic Goroutine:", message)
}
// 2. Worker Pool Pattern
func workerPool() {
const numWorkers = 3
const numJobs = 5
jobs := make(chan int, numJobs)
results := make(chan int, numJobs)
// Create workers
for i := 1; i <= numWorkers; i++ {
go worker(i, jobs, results)
}
// Send jobs
for j := 1; j <= numJobs; j++ {
jobs <- j
}
close(jobs)
// Collect results
for r := 1; r <= numJobs; r++ {
result := <-results
fmt.Printf("2. Worker Pool: Job %d result %d\n", r, result)
}
}
func worker(id int, jobs <-chan int, results chan<- int) {
for j := range jobs {
fmt.Printf("Worker %d processing job %d\n", id, j)
time.Sleep(time.Second) // Simulate work
results <- j * 2
}
}
// 3. Fan-out/Fan-in Pattern
func fanOutFanIn() {
jobs := make(chan int, 100)
results := make(chan int, 100)
// Fan-out: start multiple workers
for i := 1; i <= 3; i++ {
go func(workerID int) {
for job := range jobs {
result := job * 2
results <- result
fmt.Printf("3. Fan-out: Worker %d processed job %d\n", workerID, job)
}
}(i)
}
// Send jobs
for i := 1; i <= 5; i++ {
jobs <- i
}
close(jobs)
// Fan-in: collect results
for i := 1; i <= 5; i++ {
result := <-results
fmt.Printf("3. Fan-in: Result %d\n", result)
}
}
// 4. Pipeline Pattern
func pipeline() {
// Stage 1: Generate numbers
generator := func(done <-chan struct{}, nums ...int) <-chan int {
out := make(chan int)
go func() {
defer close(out)
for _, n := range nums {
select {
case out <- n:
case <-done:
return
}
}
}()
return out
}
// Stage 2: Square numbers
square := func(done <-chan struct{}, in <-chan int) <-chan int {
out := make(chan int)
go func() {
defer close(out)
for n := range in {
select {
case out <- n * n:
case <-done:
return
}
}
}()
return out
}
// Stage 3: Convert to string
toString := func(done <-chan struct{}, in <-chan int) <-chan string {
out := make(chan string)
go func() {
defer close(out)
for n := range in {
select {
case out <- fmt.Sprintf("Result: %d", n):
case <-done:
return
}
}
}()
return out
}
// Build pipeline
done := make(chan struct{})
defer close(done)
numbers := generator(done, 1, 2, 3, 4, 5)
squares := square(done, numbers)
strings := toString(done, squares)
// Consume results
for s := range strings {
fmt.Printf("4. Pipeline: %s\n", s)
}
}
// 5. Select Statement Pattern
func selectExample() {
ch1 := make(chan string)
ch2 := make(chan string)
go func() {
time.Sleep(100 * time.Millisecond)
ch1 <- "from channel 1"
}()
go func() {
time.Sleep(200 * time.Millisecond)
ch2 <- "from channel 2"
}()
for i := 0; i < 2; i++ {
select {
case msg1 := <-ch1:
fmt.Printf("5. Select: Received %s\n", msg1)
case msg2 := <-ch2:
fmt.Printf("5. Select: Received %s\n", msg2)
case <-time.After(1 * time.Second):
fmt.Println("5. Select: Timeout")
}
}
}
// 6. Mutex Pattern
func mutexExample() {
var counter int
var mu sync.Mutex
const numGoroutines = 1000
var wg sync.WaitGroup
wg.Add(numGoroutines)
for i := 0; i < numGoroutines; i++ {
go func() {
defer wg.Done()
mu.Lock()
counter++
mu.Unlock()
}()
}
wg.Wait()
fmt.Printf("6. Mutex: Final counter value: %d\n", counter)
}
// 7. WaitGroup Pattern
func waitGroupExample() {
var wg sync.WaitGroup
tasks := []string{"Task 1", "Task 2", "Task 3"}
for _, task := range tasks {
wg.Add(1)
go func(t string) {
defer wg.Done()
time.Sleep(time.Duration(100+time.Now().UnixNano()%100) * time.Millisecond)
fmt.Printf("7. WaitGroup: Completed %s\n", t)
}(task)
}
wg.Wait()
fmt.Println("7. WaitGroup: All tasks completed")
}
// 8. Context Pattern
func contextExample() {
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
ch := make(chan string)
go func() {
time.Sleep(3 * time.Second)
ch <- "slow operation"
}()
select {
case result := <-ch:
fmt.Printf("8. Context: Result: %s\n", result)
case <-ctx.Done():
fmt.Printf("8. Context: Timeout: %v\n", ctx.Err())
}
}
// 9. Once Pattern
func onceExample() {
var once sync.Once
var setupDone bool
setup := func() {
fmt.Println("9. Once: Setup function called")
setupDone = true
}
for i := 1; i <= 3; i++ {
go func(id int) {
once.Do(setup)
fmt.Printf("9. Once: Goroutine %d, setupDone: %t\n", id, setupDone)
}(i)
}
time.Sleep(100 * time.Millisecond)
}
// 10. Buffered Channel as Semaphore
func semaphoreExample() {
const maxConcurrency = 3
sem := make(chan struct{}, maxConcurrency)
tasks := make([]int, 10)
for i := range tasks {
tasks[i] = i + 1
}
var wg sync.WaitGroup
for _, task := range tasks {
wg.Add(1)
go func(t int) {
defer wg.Done()
// Acquire semaphore
sem <- struct{}{}
defer func() { <-sem }()
fmt.Printf("10. Semaphore: Starting task %d\n", t)
time.Sleep(time.Duration(200+time.Now().UnixNano()%300) * time.Millisecond)
fmt.Printf("10. Semaphore: Completed task %d\n", t)
}(task)
}
wg.Wait()
fmt.Println("10. Semaphore: All tasks completed")
}
// 11. Producer-Consumer Pattern
func producerConsumer() {
jobs := make(chan int, 10)
done := make(chan bool)
// Producer
go func() {
for i := 1; i <= 5; i++ {
jobs <- i
fmt.Printf("11. Producer: Sent job %d\n", i)
time.Sleep(100 * time.Millisecond)
}
close(jobs)
}()
// Consumer
go func() {
for job := range jobs {
fmt.Printf("11. Consumer: Received job %d\n", job)
time.Sleep(200 * time.Millisecond)
}
done <- true
}()
<-done
fmt.Println("11. Producer-Consumer: All jobs processed")
}
// 12. Rate Limiting Pattern
func rateLimiting() {
requests := make(chan int, 5)
for i := 1; i <= 5; i++ {
requests <- i
}
close(requests)
limiter := time.Tick(200 * time.Millisecond)
for req := range requests {
<-limiter
fmt.Printf("12. Rate Limiting: Processing request %d\n", req)
}
}
func main() {
fmt.Println("=== Go Concurrency Patterns ===")
basicGoroutine()
fmt.Println()
workerPool()
fmt.Println()
fanOutFanIn()
fmt.Println()
pipeline()
fmt.Println()
selectExample()
fmt.Println()
mutexExample()
fmt.Println()
waitGroupExample()
fmt.Println()
contextExample()
fmt.Println()
onceExample()
fmt.Println()
semaphoreExample()
fmt.Println()
producerConsumer()
fmt.Println()
rateLimiting()
fmt.Println("=== All Concurrency Patterns Completed ===")
}Bibliothèque Standard Go
Paquets de la bibliothèque standard Go et modèles d'utilisation courants
Difficulté
7/10
Temps estimé
25 min
Étiquettes
go, golang, libraries, utilities
Prérequis
Basic Go syntax
// Go Standard Library Examples
package main
import (
"fmt"
"os"
"io"
"bufio"
"encoding/json"
"net/http"
"time"
"math/rand"
"sort"
"strings"
"strconv"
"log"
"path/filepath"
"ioutil"
"compress/gzip"
"crypto/sha256"
"encoding/base64"
)
// 1. File I/O Operations
func fileOperations() {
// Write to file
content := []byte("Hello, Go Standard Library!\n")
err := ioutil.WriteFile("example.txt", content, 0644)
if err != nil {
log.Fatal(err)
}
// Read from file
data, err := ioutil.ReadFile("example.txt")
if err != nil {
log.Fatal(err)
}
fmt.Printf("1. File I/O: %s", string(data))
// Read line by line
file, err := os.Open("example.txt")
if err != nil {
log.Fatal(err)
}
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
fmt.Printf("1. Line by line: %s\n", scanner.Text())
}
// Clean up
os.Remove("example.txt")
}
// 2. HTTP Client and Server
func httpExamples() {
// HTTP Client
resp, err := http.Get("https://httpbin.org/get")
if err != nil {
log.Printf("HTTP request failed: %v", err)
return
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Printf("Failed to read response: %v", err)
return
}
fmt.Printf("2. HTTP Response status: %s\n", resp.Status)
fmt.Printf("2. HTTP Response length: %d bytes\n", len(body))
// Simple HTTP Server (would run in separate goroutine in real app)
fmt.Println("2. HTTP Server example (commented out for safety)")
/*
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, World!")
})
go func() {
log.Fatal(http.ListenAndServe(":8080", nil))
}()
*/
}
// 3. JSON Encoding/Decoding
func jsonExamples() {
type Person struct {
Name string `json:"name"`
Age int `json:"age"`
City string `json:"city,omitempty"`
}
// Encode JSON
person := Person{
Name: "Alice",
Age: 30,
City: "New York",
}
jsonData, err := json.Marshal(person)
if err != nil {
log.Fatal(err)
}
fmt.Printf("3. JSON Encoded: %s\n", string(jsonData))
// Decode JSON
var decodedPerson Person
err = json.Unmarshal(jsonData, &decodedPerson)
if err != nil {
log.Fatal(err)
}
fmt.Printf("3. JSON Decoded: %+v\n", decodedPerson)
// Pretty print JSON
prettyJSON, err := json.MarshalIndent(person, "", " ")
if err != nil {
log.Fatal(err)
}
fmt.Printf("3. Pretty JSON:\n%s\n", string(prettyJSON))
}
// 4. Time and Duration
func timeExamples() {
now := time.Now()
fmt.Printf("4. Current time: %s\n", now.Format("2006-01-02 15:04:05"))
// Parse time
layout := "2006-01-02"
str := "2024-01-15"
t, err := time.Parse(layout, str)
if err != nil {
log.Fatal(err)
}
fmt.Printf("4. Parsed time: %s\n", t.Format(layout))
// Duration
duration := 2 * time.Hour + 30 * time.Minute
fmt.Printf("4. Duration: %s\n", duration)
// Time operations
future := now.Add(24 * time.Hour)
fmt.Printf("4. Tomorrow: %s\n", future.Format("2006-01-02"))
// Unix timestamp
timestamp := now.Unix()
fmt.Printf("4. Unix timestamp: %d\n", timestamp)
}
// 5. Math and Random
func mathExamples() {
// Basic math
fmt.Printf("5. Pi: %f\n", 3.14159)
fmt.Printf("5. Square root: %f\n", 16.0)
// Random numbers
rand.Seed(time.Now().UnixNano())
randomInt := rand.Intn(100)
fmt.Printf("5. Random number: %d\n", randomInt)
randomFloat := rand.Float64()
fmt.Printf("5. Random float: %f\n", randomFloat)
// Random choice from slice
colors := []string{"red", "green", "blue", "yellow"}
randomColor := colors[rand.Intn(len(colors))]
fmt.Printf("5. Random color: %s\n", randomColor)
}
// 6. Sort Operations
func sortExamples() {
// Sort integers
numbers := []int{64, 34, 25, 12, 22, 11, 90}
sort.Ints(numbers)
fmt.Printf("6. Sorted integers: %v\n", numbers)
// Sort strings
words := []string{"banana", "apple", "cherry", "date"}
sort.Strings(words)
fmt.Printf("6. Sorted strings: %v\n", words)
// Custom sort
type Person struct {
Name string
Age int
}
people := []Person{
{"Alice", 30},
{"Bob", 25},
{"Charlie", 35},
}
sort.Slice(people, func(i, j int) bool {
return people[i].Age < people[j].Age
})
fmt.Printf("6. Sorted by age: %+v\n", people)
// Search in sorted slice
index := sort.SearchInts(numbers, 25)
fmt.Printf("6. Search result: index %d\n", index)
}
// 7. String Operations
func stringExamples() {
text := "Hello, Go Standard Library!"
// Basic operations
fmt.Printf("7. Length: %d\n", len(text))
fmt.Printf("7. Upper: %s\n", strings.ToUpper(text))
fmt.Printf("7. Lower: %s\n", strings.ToLower(text))
fmt.Printf("7. Contains 'Go': %t\n", strings.Contains(text, "Go"))
// Split and join
words := strings.Split(text, " ")
fmt.Printf("7. Split: %v\n", words)
joined := strings.Join(words, "-")
fmt.Printf("7. Joined: %s\n", joined)
// Trim and replace
trimmed := strings.TrimSpace(" Hello ")
fmt.Printf("7. Trimmed: '%s'\n", trimmed)
replaced := strings.Replace(text, "Go", "Golang", 1)
fmt.Printf("7. Replaced: %s\n", replaced)
// Conversion
numStr := "123"
num, err := strconv.Atoi(numStr)
if err == nil {
fmt.Printf("7. String to int: %d\n", num)
}
floatStr := "3.14"
floatNum, err := strconv.ParseFloat(floatStr, 64)
if err == nil {
fmt.Printf("7. String to float: %f\n", floatNum)
}
}
// 8. File Path Operations
func pathExamples() {
// Join paths
path := filepath.Join("home", "user", "documents", "file.txt")
fmt.Printf("8. Joined path: %s\n", path)
// Get path components
dir := filepath.Dir(path)
base := filepath.Base(path)
ext := filepath.Ext(path)
fmt.Printf("8. Directory: %s\n", dir)
fmt.Printf("8. Base name: %s\n", base)
fmt.Printf("8. Extension: %s\n", ext)
// Absolute path
absPath, err := filepath.Abs(".")
if err == nil {
fmt.Printf("8. Absolute path: %s\n", absPath)
}
// Path operations
isAbs := filepath.IsAbs("/absolute/path")
fmt.Printf("8. Is absolute: %t\n", isAbs)
}
// 9. Compression Examples
func compressionExamples() {
// Compress data
data := []byte("Hello, World! This is a test string for compression.")
var buf bytes.Buffer
writer := gzip.NewWriter(&buf)
writer.Write(data)
writer.Close()
compressed := buf.Bytes()
fmt.Printf("9. Original size: %d\n", len(data))
fmt.Printf("9. Compressed size: %d\n", len(compressed))
// Decompress
reader, err := gzip.NewReader(bytes.NewReader(compressed))
if err != nil {
log.Fatal(err)
}
defer reader.Close()
decompressed, err := ioutil.ReadAll(reader)
if err != nil {
log.Fatal(err)
}
fmt.Printf("9. Decompressed: %s\n", string(decompressed))
}
// 10. Cryptography Examples
func cryptoExamples() {
// SHA256 hash
data := []byte("Hello, World!")
hash := sha256.Sum256(data)
fmt.Printf("10. SHA256: %x\n", hash)
// Base64 encoding
encoded := base64.StdEncoding.EncodeToString(data)
fmt.Printf("10. Base64 encoded: %s\n", encoded)
// Base64 decoding
decoded, err := base64.StdEncoding.DecodeString(encoded)
if err != nil {
log.Fatal(err)
}
fmt.Printf("10. Base64 decoded: %s\n", string(decoded))
}
func main() {
fmt.Println("=== Go Standard Library Examples ===")
fileOperations()
fmt.Println()
httpExamples()
fmt.Println()
jsonExamples()
fmt.Println()
timeExamples()
fmt.Println()
mathExamples()
fmt.Println()
sortExamples()
fmt.Println()
stringExamples()
fmt.Println()
pathExamples()
fmt.Println()
compressionExamples()
fmt.Println()
cryptoExamples()
fmt.Println("=== All Standard Library Examples Completed ===")
}Outils
Outils souvent utilisés avec cet exemple
Associé