Go(Golang)的十个常见代码片段用于各种任务

开发 后端
提供“前10名”Go代码片段的明确列表是具有挑战性的,因为代码片段的实用性取决于您试图解决的具体问题。然而,我可以为您提供十个常用的Go代码片段,涵盖了各种任务和概念。

探索有用的Go编程代码片段

提供“前10名”Go(Golang)代码片段的明确列表是具有挑战性的,因为代码片段的实用性取决于您试图解决的具体问题。然而,我可以为您提供十个常用的Go代码片段,涵盖了各种任务和概念:

1. Hello World:

package main

import "fmt"

func main() {
    fmt.Println("Hello, World!")
}

2. Reading Input from Console:

package main

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

func main() {
    scanner := bufio.NewScanner(os.Stdin)
    fmt.Print("Enter text: ")
    scanner.Scan()
    input := scanner.Text()
    fmt.Println("You entered:", input)
}

3. Creating a Goroutine:

package main

import (
    "fmt"
    "time"
)

func printNumbers() {
    for i := 1; i <= 5; i++ {
        fmt.Println(i)
        time.Sleep(time.Second)
    }
}

func main() {
    go printNumbers()
    time.Sleep(3 * time.Second)
}

4. Working with Slices:

package main

import "fmt"

func main() {
    numbers := []int{1, 2, 3, 4, 5}
    fmt.Println("Slice:", numbers)
    fmt.Println("Length:", len(numbers))
    fmt.Println("First Element:", numbers[0])
}

5. Error Handling:

package main

import (
    "errors"
    "fmt"
)

func divide(a, b float64) (float64, error) {
    if b == 0 {
        return 0, errors.New("division by zero")
    }
    return a / b, nil
}

func main() {
    result, err := divide(10, 2)
    if err != nil {
        fmt.Println("Error:", err)
        return
    }
    fmt.Println("Result:", result)
}

6. HTTP Server:

package main

import (
    "fmt"
    "net/http"
)

func handler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintln(w, "Hello, HTTP!")
}

func main() {
    http.HandleFunc("/", handler)
    http.ListenAndServe(":8080", nil)
}

7. JSON Marshalling and Unmarshalling:

package main

import (
    "fmt"
    "encoding/json"
)

type Person struct {
    Name  string `json:"name"`
    Age   int    `json:"age"`
}

func main() {
    jsonStr := `{"name":"Alice", "age":30}`
    var person Person
    err := json.Unmarshal([]byte(jsonStr), &person)
    if err != nil {
        fmt.Println("Error:", err)
        return
    }
    fmt.Println("Name:", person.Name)
    fmt.Println("Age:", person.Age)
}

8. Concurrency with Wait Groups:

package main

import (
    "fmt"
    "sync"
)

func worker(id int, wg *sync.WaitGroup) {
    defer wg.Done()
    fmt.Printf("Worker %d started\n", id)
}

func main() {
    var wg sync.WaitGroup
    for i := 1; i <= 5; i++ {
        wg.Add(1)
        go worker(i, &wg)
    }
    wg.Wait()
    fmt.Println("All workers have finished.")
}

9. Reading and Writing Files:

package main

import (
    "fmt"
    "io/ioutil"
)

func main() {
    data := []byte("Hello, File!")
    err := ioutil.WriteFile("example.txt", data, 0644)
    if err != nil {
        fmt.Println("Error:", err)
        return
    }
    content, err := ioutil.ReadFile("example.txt")
    if err != nil {
        fmt.Println("Error:", err)
        return
    }
    fmt.Println("File Content:", string(content))
}

10. Sorting Slices:

package main

import (
    "fmt"
    "sort"
)

func main() {
    numbers := []int{5, 2, 9, 1, 5}
    sort.Ints(numbers)
    fmt.Println("Sorted Slice:", numbers)
}

这些代码片段涵盖了从基本的I/O操作到并发、错误处理等常见Go编程任务和概念。请随意根据您在Go项目中的需要进行调整和使用。

责任编辑:赵宁宁 来源: GameOfTech
相关推荐

2012-01-17 13:54:02

PHP

2024-04-09 00:00:00

Java代码片段

2024-05-13 12:36:51

Python代码

2022-11-25 14:55:43

JavaScriptweb应用程序

2022-07-30 23:35:49

软件开发代码编辑器Web

2023-05-28 22:48:29

程序员编程

2023-10-07 11:36:15

2022-12-04 23:39:33

机器学习AutoML

2022-07-31 23:54:24

Linux操作系统

2023-02-14 08:10:14

Python人工智能XAI

2022-07-31 23:53:37

Linux操作系统设备

2023-12-22 16:48:00

Kubernetes容器集群

2023-12-26 14:28:08

JavaScript开发

2024-09-30 10:05:00

2010-03-04 16:09:09

2012-11-08 09:37:45

代码编程语言

2024-09-24 07:57:55

SQL错误​​EXPLAIN​

2023-07-14 14:25:00

Python语言错误

2022-07-06 08:39:33

Python代码

2021-11-04 09:10:22

CSS 技巧代码重构
点赞
收藏

51CTO技术栈公众号