探索有用的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
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
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项目中的需要进行调整和使用。
领取专属 10元无门槛券
私享最新 技术干货