GO-使用标准库

GO-使用标准库
怀光1. fmt
包
fmt
包用于格式化输入和输出,提供了便捷的函数来打印数据和格式化字符串。
常用函数
fmt.Print
、fmt.Println
:直接输出到控制台。fmt.Printf
:支持格式化输出。fmt.Sprintf
:格式化并返回字符串。
示例
1 | name := "Alice" |
2. math
包
math
包提供了数学运算的基础函数,包括基本的数学计算、三角函数、对数函数等。
常用函数
- 基本运算:
math.Abs
、math.Max
、math.Min
。 - 指数运算:
math.Pow
、math.Sqrt
。 - 三角函数:
math.Sin
、math.Cos
、math.Tan
。
示例
1 | a, b := 3.0, 4.0 |
3. time
包
time
包用于处理时间和日期,是处理时间戳、格式化时间和计算时间差的必备工具。
常用函数
- 获取当前时间:
time.Now
。 - 时间格式化:
t.Format("2006-01-02 15:04:05")
。 - 时间解析:
time.Parse
。 - 时间计算:
time.Add
、time.Sub
。
示例
1 | now := time.Now() |
4. strings
包
strings
包提供了对字符串的常用操作,如拼接、分割、替换等。
常用函数
strings.ToUpper
、strings.ToLower
:大小写转换。strings.Contains
:判断子字符串是否存在。strings.Split
、strings.Join
:分割和拼接字符串。
示例
1 | text := "hello, world" |
5. io
和 ioutil
包
io
和 ioutil
包用于文件和流操作,提供了文件读写的常用工具。
常用函数
- 文件读取:
ioutil.ReadFile
。 - 文件写入:
ioutil.WriteFile
。 - 文件复制:
io.Copy
。
示例
1 | data, err := ioutil.ReadFile("example.txt") |
6. net/http
包
net/http
包提供了构建 HTTP 客户端和服务器的基础工具,是 Go 语言中开发网络应用的核心库。
常用函数
- 服务器端:
http.ListenAndServe
、http.HandleFunc
。 - 客户端请求:
http.Get
、http.Post
。
示例
1 | http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { |