Files
notes/resource/go/待总结/009 Go 语言常用包.md
2026-03-01 01:43:46 +08:00

294 lines
7.6 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# strconv
bool - 字符串 ,“true” = 转换 true
数字 - 字符串, “3.99” / 转换为数字才可以进行计算
```go
package main
import (
"fmt"
"strconv"
)
// 项目:前端(网页、小程序、app) 后端代码-接收前端的请求
/*
func http(request) response{
string:= request.getUrlParm
// 数据库
// 计算
// 字符串的转换
}
*/
// string convert = strconv
func main() {
// bool
s1 := "true"
// 转化 - 字符串转bool(解析:parse
// func ParseBool(str string) (bool, error)
b1, err := strconv.ParseBool(s1)
if err != nil {
fmt.Println(err)
return
}
fmt.Printf("%T,%t\n", b1, b1) // bool,true
// bool转字符串(格式化 format
s2 := strconv.FormatBool(b1)
fmt.Printf("%T,%s\n", s2, s2) // string,true
// 整数->字符串 Format 字符串->整数
s3 := "100000"
// 整数: 数字、进制、大小
// 参数:1、str 2、 进制(10) 3、大小
i1, _ := strconv.ParseInt(s3, 10, 64)
fmt.Printf("%T,%d\n", i1, i1) // int64,100
s4 := strconv.FormatInt(i1, 10)
fmt.Printf("%T,%s\n", s4, s4) // string,100000
// 10进制转换字符串,简便方法 atoi itoa
atoi, _ := strconv.Atoi("-20")
fmt.Printf("%T,%d\n", atoi, atoi) // int,-20
itoa := strconv.Itoa(30)
fmt.Printf("%T,%s\n", itoa, itoa) // string,30
}
```
# time 时间
一切的代码,都是为了解决现实生活中可能出现的业务,时间是很重要的。
time 包
- 获取当前时间
- 格式化时间
```go
package main
import (
"fmt"
"time"
)
// time
func main() {
}
// 获取当前时间 now
func time1() {
// 返回值为Time结构体 : 常量:日月年时分秒 周日-周六 方法:获取常量,计算。
now := time.Now()
year := now.Year()
month := now.Month()
day := now.Day()
hour := now.Hour()
minute := now.Minute()
second := now.Second()
// 2023-2-23 20:40:31
// Printf : 整数补位--02如果不足两位,左侧用0补齐输出
fmt.Printf("%d-%02d-%02d %02d:%02d:%02d\n", year, month, day, hour, minute, second)
}
func time2() {
//time1()
// 打印时间
now := time.Now()
// 时间格式化 2023-02-23 20:43:49
// 格式化模板: yyyy-MM-dd HH:mm:ss
// Go语言诞生的时间作为格式化模板:2006年1月2号下午3点4分
// Go语言格式化时间的代码:2006-01-02 15:04:05 (记忆方式:2006 12 345
// 固定的:"2006-01-02 15:04:05"
fmt.Println(now.Format("2006-01-02 15:04:05")) // 24小时制
fmt.Println(now.Format("2006-01-02 03:04:05 PM")) // 12小时制
fmt.Println(now.Format("2006/01/02 15:04")) // 2023/02/23 20:52
fmt.Println(now.Format("15:04 2006/01/02")) // 20:52 2023/02/23
fmt.Println(now.Format("2006/01/02")) // 2023/02/23
}
// 将字符串格式化为Time对象 (获取到网页传递的时间字符串,需要转化为Time才能在代码中使用)
func time3() {
// 其他地方的时区格式:https://www.zeitverschiebung.net/cn/all-time-zones.html
// 获取时间的时区 // "Asia/Shanghai" 必须要大写 手动构建 ,如果不对,会报未知的时间错误
loc, err := time.LoadLocation("Asia/Shanghai")
if err != nil {
fmt.Println(err)
return
}
// 将字符串解析为时间 Time
timeStr := "2023-02-23 20:53:08"
// layout 格式 时间字符串 时区位置 , 需要和前端传递的格式进行匹配
// func ParseInLocation(layout, value string, loc *Location)
timeObj, _ := time.ParseInLocation("2006-01-02 15:04:05", timeStr, loc)
fmt.Println(timeObj)
}
// 时间戳:更多时候和随机数结合
func time4() {
// 格林威治时间自1970年1月1日(00:00:00 GMT)至当前时间的总秒数
// 时间戳 Unix 1970.1.1 00:00:00 - 当下的一个毫秒数,Unix 时间戳,不会重复的。
now := time.Now()
timestamp1 := now.Unix() // 时间戳
timestamp2 := now.UnixNano() // 纳秒的时间数
fmt.Println(timestamp1)
fmt.Println(timestamp2)
//
// 通过 Unix 转换time对象
timeObj := time.Unix(timestamp1, 0) // 返回time对象
year := timeObj.Year()
month := timeObj.Month()
day := timeObj.Day()
hour := timeObj.Hour()
minute := timeObj.Minute()
second := timeObj.Second()
// 2023-2-23 20:40:31
// Printf : 整数补位--02如果不足两位,左侧用0补齐输出
fmt.Printf("%d-%02d-%02d %02d:%02d:%02d\n", year, month, day, hour, minute, second)
}
```
# 随机数
```go
package main
import (
"fmt"
"math/rand"
"time"
)
// random随机数- math/rand
func main() {
// 获取一个随机数
num1 := rand.Int()
fmt.Println("num1:", num1) // 5577006791947779410
// 随机需要一个随机数的种子,如果种子一样,那么结果一致
// n范围(0-n
num2 := rand.Intn(100)
fmt.Println("num2:", num2) // 7
// 需要一个随时都在发生变化的量 时间戳
timestamp := time.Now().Unix()
// 设置随机数种子, 使用时间戳
// 种子只需要设置一次即可。
rand.Seed(timestamp) // 每次执行都不同
for i := 0; i < 5; i++ {
// Intn [0,n)
// 20-29
num1 := rand.Intn(200) // 抽奖程序
// 必中的逻辑
num2 := rand.Intn(5) // 抽奖程序
if i == num2 {
fmt.Println(10)
continue
}
fmt.Println(num1)
}
}
```
# 定时器-时间操作
> 时间间隔常量 Duration
time.Duration是time包定义的一个类型,它代表两个时间点之间经过的时间
以纳秒为单位,可表示的最长时间段大约290年。
time包中定义的时间间隔类型的常量如下:
```go
const (
Nanosecond Duration = 1
Microsecond = 1000 * Nanosecond
Millisecond = 1000 * Microsecond
Second = 1000 * Millisecond
Minute = 60 * Second
Hour = 60 * Minute
)
```
time.Duration表示1纳秒,time.Second表示1秒。
> 定时器
```go
// 定时器: 每隔xxx s执行一次, 其余的关于定时器,放到chan讲
ticker := time.Tick(time.Second) // 每一秒都会触发。
for i := range ticker {
fmt.Println(i)
}
```
> 时间判断
```go
package main
import (
"fmt"
"time"
)
func main() {
// 加 减 比较(在xxx之前 在xxx之后 相等)
now := time.Now()
later := now.Add(time.Hour)
fmt.Println(later)
// 两个时间的差值
subTime := later.Sub(now)
fmt.Println(subTime) // 1h0m0s
// 比较时间, init() 校验时间 当地时间和网络时间是否一致
fmt.Println(now.Equal(later)) // fasle
fmt.Println(now.Before(later)) // true
fmt.Println(now.After(later)) // fasle
}
// 定时器 - 本质是一个通道chan
func d1() {
// 定时器: 每隔xxx s执行一次, 其余的关于定时器,放到chan讲
ticker := time.Tick(time.Second) // 每一秒都会触发。
for i := range ticker {
fmt.Println(i)
}
}
```
小案例:
```go
package main
import (
"syscall"
"time"
"unsafe"
)
func main() {
ticker := time.Tick(time.Second) // 每一秒都会触发。
for i := range ticker {
msgBox(i.Format("2006-01-02 15:04:05"))
}
}
func msgBox(timeStr string) {
user32 := syscall.NewLazyDLL("user32.dll")
messageBox := user32.NewProc("MessageBoxW")
hwnd := 0 // 0表示将弹窗放在桌面的中心位置
title := "Hello"
text := timeStr
flags := 0x00000000 | 0x00000040 // 0x00000000表示弹出消息框并且默认按钮为OK,0x00000040表示消息框的图标为信息图标
messageBox.Call(uintptr(hwnd), uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr(text))), uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr(title))), uintptr(flags))
}
```