ARTICLE DETAIL

资讯详情

深耕编程入门与网站建设的一线实战洞察。

Go 语言标准库最简教程

Go 语言标准库最简教程 按日常开发中使用频率从高到低介绍Go标准库中最常用、最该优先掌握的包并给出极简示例。1.格式化输出package main import fmt func main() { fmt.Println(hello) // 打印 换行 fmt.Printf(%d\n, 10) // 格式化 fmt.Sprintf(val%d, 5) // 返回字符串 fmt.Scan(x) // 读取输入 }2. 字符串处理与类型转换package main import ( strings strconv ) func main() { strings.Contains(hello, ell) // true strings.Split(a,b,c, ,) // [a b c] strings.Join([]string{a,b},-)// a-b strings.TrimSpace( hi ) // hi i, _ : strconv.Atoi(123) // string - int s : strconv.Itoa(123) // int - string }3. 文件与系统package main import ( os bufio io ) func main() { // 写文件 os.WriteFile(a.txt, []byte(hi), 0644) // 读文件 data, _ : os.ReadFile(a.txt) // 按行读取大文件推荐 f, _ : os.Open(a.txt) defer f.Close() sc : bufio.NewScanner(f) for sc.Scan() { fmt.Println(sc.Text()) } // 拷贝 io.Copy(dst, src) }4. 时间日期package main import time func main() { now : time.Now() fmt.Println(now.Format(2006-01-02 15:04:05)) // Go 固定参考时间 time.Sleep(2 * time.Second) t, _ : time.Parse(2006-01-02, 2026-09-13) fmt.Println(t.Year()) }5. HTTP 服务与请求package main import ( net/http io ) func main() { // 启动 Web 服务 http.HandleFunc(/, func(w http.ResponseWriter, r *http.Request) { io.WriteString(w, Hello Go) }) http.ListenAndServe(:8080, nil) // 发起 GET 请求 resp, _ : http.Get(https://go.dev) defer resp.Body.Close() body, _ : io.ReadAll(resp.Body) }6. 排序与切片操作package main import ( sort slices encoding/json ) type User struct { Name string json:name Age int json:age } func main() { nums : []int{3, 1, 2} sort.Ints(nums) // [1 2 3] slices.Sort(nums) // Go 1.21 更简洁 tom : User{Tom, 18} jhon : User{Jhon, 19} users : []User{tom, jhon} sort.Slice(users, func(i, j int) bool { return users[i].Age users[j].Age }) }7. 错误处理增强package main import ( errors fmt ) func main() { err : errors.New(something wrong) wrapped : fmt.Errorf(read failed: %w, err) // 包装错误 errors.Is(wrapped, err) // true }8. 超时与取消context高并发 / 网络请求必备。package main import ( fmt context time ) func main() { ctx, cancel : context.WithTimeout(context.Background(), 3*time.Second) defer cancel() select { case -time.After(5 * time.Second): fmt.Println(too slow) case -ctx.Done(): fmt.Println(timeout:, ctx.Err()) } }9. 数学与随机package main import ( fmt math math/rand ) func main() { s : math.Sqrt(16) // 4 fmt.println(math.Sqrt(6): , s) i : rand.Intn(100) // 0~99 随机 fmt.println(rand.Intn(100): , i) r : rand.New(rand.NewSource(time.Now().UnixNano())) fmt.println(rand.New(rand.NewSource(time.Now().UnixNano())): , 4) }10.标准库文档标准库文档学习建议先熟fmt、strings、os、time。Web开发需掌握net/httpencoding/json。掌握这9 类已覆盖 90%的日常工作场景。
返回列表