当前位置:首页 > 科技  > 软件

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

来源: 责编: 时间:2024-01-03 09:12:31 147观看
导读探索有用的Go编程代码片段提供“前10名”Go(Golang)代码片段的明确列表是具有挑战性的,因为代码片段的实用性取决于您试图解决的具体问题。然而,我可以为您提供十个常用的Go代码片段,涵盖了各种任务和概念:1. Hello World:p

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

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

or728资讯网——每日最新资讯28at.com

1. Hello World:

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

2. Reading Input from Console:

package mainimport (    "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 mainimport (    "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 mainimport "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 mainimport (    "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 mainimport (    "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 mainimport (    "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 mainimport (    "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 mainimport (    "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 mainimport (    "fmt"    "sort")func main() {    numbers := []int{5, 2, 9, 1, 5}    sort.Ints(numbers)    fmt.Println("Sorted Slice:", numbers)}

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

本文链接:http://www.28at.com/showinfo-26-56586-0.htmlGo(Golang)的十个常见代码片段用于各种任务

声明:本网页内容旨在传播知识,若有侵权等问题请及时与本网联系,我们将在第一时间删除处理。邮件:2376512515@qq.com

上一篇: 万字+20张图探秘Nacos注册中心核心实现原理

下一篇: PyCharm必备,七个实用插件助你事半功倍

标签:
  • 热门焦点
Top