Elysia Tools

在一个清晰的工作台里浏览工具、案例、可视化和主题指南。

热门分类

专题

语言
ZHDERUPTENFRES

Elysia Tools

导航

编程语言

Go 示例

Go (Golang) 代码示例和Hello World演示

案例

这个案例集合中的条目

代码go简单

Go Hello World

Go Hello World程序和基本语法示例

难度

3/10

预计时间

15 min

标签

go, golang, programming, concurrency

前置条件

Basic programming concepts

go
// 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))
}
代码go中等

Go 并发模式

高级Go并发模式,包含goroutines、channels和同步原语

难度

8/10

预计时间

30 min

标签

go, golang, concurrency, patterns

前置条件

Basic Go syntax

go
// 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 ===")
}
代码go中等

Go 标准库示例

Go标准库包和常用模式

难度

7/10

预计时间

25 min

标签

go, golang, libraries, utilities

前置条件

Basic Go syntax

go
// 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 ===")
}

工具

经常与该案例搭配使用的工具

相关内容

相关案例集合

相关内容

相关专题

专题

JSON 到强类型代码生成器

从 JSON 或 schema 证据生成 TypeScript、Go、Rust、Kotlin、Java、C# 与 Zod 校验模型。

专题

药代动力学教学模型与结果核查

用于教学或 QA 的药代公式、模型假设和结果一致性核查,不提供用药剂量、诊断或临床建议。

专题

图片、PDF 与视频品牌水印交付

在受控交付前,为图片、PDF 和视频选择、应用并核验清晰可读的品牌水印。

专题

经典与现代密码工具

在安全的教学或 CTF 场景中比较可逆的经典变换与现代加密,并明确玩具密码不等于安全防护。

首页
工具3212
案例593
可视化471
文件查看器103
专题239
标签333
图像、音频与视频657

图像、音频、视频处理、转换与优化工具

数学、日期与金融647

计算器、数值计算、日期逻辑、统计与金融工具

设计与颜色298

颜色、版式、图形、视觉样式与设计辅助工具

文本与写作209

写作、清洗、格式化、提取与文本分析工具

开发与 Web193

开发者工具、网络处理、Web 调试与自动化辅助工具

转换与编码175

格式、文件、压缩包、单位与编码转换工具

潜客测验发布与联系人交接
讣告、悼词与纪念卡的家属复核及交付
本地习惯记录的备份、恢复演练与分享前检查
长文改编 X 串文与 LinkedIn 帖子的事实复核与交付
Markdown 互动课件审校、离线演示与交付

© 2026 Elysia Tools. 保留所有权利。

文档价格关于我们服务条款隐私政策Cookie 政策联系我们
编程语言

C++ 示例

C++ 代码示例和Hello World演示

编程语言

Java 示例

Java代码示例和Hello World演示

编程语言

JavaScript 示例

JavaScript代码示例和Hello World演示

编程语言

Python 示例

Python代码示例和Hello World演示

编程语言

TypeScript 示例

TypeScript代码示例,包含类型安全和Hello World演示

编程语言

Zig 示例

Zig编程语言示例 - 简单、高效的系统编程,具有内存安全性