GO - 标准库

go - 标准库

标准库参考地址

bash 复制代码
https://golang.google.cn/pkg/

标准库说明

数据处理

encoding/(例如:encoding/json、encoding/xml、encoding/base64)
hash/
(例如:hash/adler32、hash/crc32、hash/fnv)

bytes

strconv
文件操作

os

path/(例如:path/filepath)
bufio
compress/
(例如:compress/gzip、compress/zlib)
网络通信

net

net/http

net/http/(例如:net/http/httputil、net/http/pprof)
net/url
net/rpc
net/smtp
加密和安全
crypto/
(例如:crypto/md5、crypto/aes、crypto/rsa)

crypto/rand

crypto/tls

crypto/x509
时间处理

time
容器和集合

container/(例如:container/heap、container/list)
sort
并发和同步
sync/
(例如:sync/atomic)

runtime

runtime/pprof

runtime/trace
测试和调试

testing

testing/(例如:testing/iotest、testing/quick)
文本处理
fmt
strings
unicode/
(例如:unicode/utf8、unicode/utf16)

text/(例如:text/template、text/scanner)
其他
errors
flag
log
math
math/
(例如:math/big、math/rand)

sync/atomic

unsafe

示例

文件操作示例(os、path/filepath、bufio)

go 复制代码
package main

import (
    "os"
    "path/filepath"
    "bufio"
)

func main() {
    // 创建文件
    file, err := os.Create("example.txt")
    if err != nil {
        panic(err)
    }
    defer file.Close()

    // 写入文件
    writer := bufio.NewWriter(file)
    _, err = writer.WriteString("Hello, World!\n")
    if err != nil {
        panic(err)
    }
    writer.Flush()

    // 读取目录
    files, err := filepath.Glob("*.txt")
    if err != nil {
        panic(err)
    }
    for _, f := range files {
        println(f)
    }
}

网络通信示例(net/http、net/url)

go 复制代码
package main

import (
    "net/http"
    "net/url"
)

func main() {
    // 发送 HTTP 请求
    resp, err := http.Get("https://www.example.com")
    if err != nil {
        panic(err)
    }
    defer resp.Body.Close()

    // 解析 URL
    u, err := url.Parse("https://www.example.com/path?query=value")
    if err != nil {
        panic(err)
    }
    println("Host:", u.Host)
    println("Path:", u.Path)
    println("Query:", u.Query().Get("query"))
}

并发和同步示例(sync)

go 复制代码
package main

import (
    "sync"
    "time"
)

func main() {
    var wg sync.WaitGroup
    wg.Add(2)

    go func() {
        defer wg.Done()
        time.Sleep(time.Second)
        println("Goroutine 1 completed")
    }()

    go func() {
        defer wg.Done()
        time.Sleep(2 * time.Second)
        println("Goroutine 2 completed")
    }()

    wg.Wait()
    println("All goroutines completed")
}
相关推荐
冒泡的肥皂11 分钟前
MVCC初学demo(一
数据库·后端·mysql
啊阿狸不会拉杆31 分钟前
《算法导论》第 32 章 - 字符串匹配
开发语言·c++·算法
颜如玉1 小时前
ElasticSearch关键参数备忘
后端·elasticsearch·搜索引擎
卡拉叽里呱啦2 小时前
缓存-变更事件捕捉、更新策略、本地缓存和热key问题
分布式·后端·缓存
David爱编程2 小时前
线程调度策略详解:时间片轮转 vs 优先级机制,面试常考!
java·后端
武当豆豆2 小时前
C++编程学习(第25天)
开发语言·c++·学习
码事漫谈3 小时前
C++继承中的虚函数机制:从单继承到多继承的深度解析
后端
阿冲Runner3 小时前
创建一个生产可用的线程池
java·后端
写bug写bug3 小时前
你真的会用枚举吗
java·后端·设计模式
喵手4 小时前
如何利用Java的Stream API提高代码的简洁度和效率?
java·后端·java ee