Go 常见包的使用

61 阅读3分钟

strconv

字符串转换成整数, bool, float,... (解析)

整数, bool, float, double, ... 转换成 字符串 (格式化)

package main

import (
	"fmt"
	"strconv"
)

func main() {
	// 字符串 -> bool(解析), bool -> 字符串 (格式化)
	s1 := "true"
	p1, _ := strconv.ParseBool(s1)
	fmt.Printf("变量类型%T,变量值为%t\n", p1, p1) // 变量类型bool,变量值为true
	// bool -> 字符串
	p2 := strconv.FormatBool(p1)
	fmt.Printf("变量类型%T,变量值为%s\n", p2, p2) // 变量类型string,变量值为true
	// 字符串 -> int, float, double ... 与上面类似的
	// 字符串 转 int 需要传入 字符串,进制,数字大小
	s3 := "127"
	i1, err := strconv.ParseInt(s3, 2, 8)
	if err != nil {
		fmt.Println(err) // strconv.ParseInt: parsing "127": invalid syntax
	}
	fmt.Printf("变量类型%T,变量值为%d\n", i1, i1) // 变量类型int64,变量值为0
	// 十进制转换字符串的简便方法 ( atoi, itoa)
	a1, _ := strconv.Atoi(s3)
	fmt.Printf("变量类型%T,变量值为%d\n", a1, a1) // 变量类型int,变量值为127
	i2 := strconv.Itoa(100)
	fmt.Printf("变量类型%T,变量值为%s\n", i2, i2) // 变量类型string,变量值为100
}

time

time包

  • 获取当前时间
  • 格式化时间
package main

import (
	"fmt"
	"time"
)

func main() {
	// 返回值为Time结构体 里面有许多常量 如: 如月年时分秒 以及一些计算时间的方法
	now := time.Now()
	year := now.Year()
	month := now.Month()
	day := now.Day()
	hour := now.Hour()
	minute := now.Minute()
	second := now.Second()
	// fmt.Printf 的用法 %.x 保留小数点后x为 %0xd 整数部位, 若位数不够 数字前用0来补
	fmt.Printf("%d-%02d-%d %d:%d:%d\n", year, month, day, hour, minute, second)
	// 输出的时候 可以使用 now.Format("") 来定输出时间格式
	// 是以Go语言诞生的时间做未格式化模板: 200612日下午34分
	// 格式化时间的代码 2006-01-02 15:04:05
	fmt.Println(now.Format("2006-01-02 15:04:05 PM")) // 12 小时
	fmt.Println(now.Format("2006-01-02 03:04:05 "))   // 24 小时
	// 获取时间的时区 必须首字母大写, 手动创建; 如果错误, 会报未知的时间错误
	// 时区可以在这里查找~ https://www.zeitverschiebung.net/cn/all-time-zones.html
	loc, err := time.LoadLocation("Asia/Shanghai")
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(loc)
	// 将字符串解析成时间 (转化成Time对象)
	timestr := "2023-02-04 11:49:56"
	// layout(格式 但时间要是Go语言诞生那个)要与字符串匹配 待解析的字符串 失去位置
	times, _ := time.ParseInLocation("2006-01-02 15:04:05", timestr, loc)
	fmt.Println(times)
	fmt.Printf("%T\n", times)

	// 时间戳 从 1970.1.1 08:00:00 -> 到当下的一个毫秒数 (不会重复的)
	fmt.Println(now.Unix())     // 毫秒时间戳
	fmt.Println(now.UnixNano()) // 纳秒时间戳
	// 通过 Unix转换成time对象
	u1 := time.Unix(now.Unix(), 0)
	fmt.Printf("%T\n", u1) // 返回time对象
	fmt.Println(u1)
}

随机数:

简单的小应用:

package main

import (
	"fmt"
	"math/rand"
	"time"
)

// random随机数 - math/rand
func main() {
	// 获取一个随机数
	// 需要一个随机数种子, 如果种子不一样, 产生的随机数结果才不一样~
	// 种子设置一次即可~
	timestamp := time.Now().Unix()
	rand.Seed(timestamp)
	num1 := rand.Intn(10) // 里面的参数 说明是一个范围 [0~n)
	fmt.Println(num1)     // 每次输出都不一样的~
}

定时器

定时器本质是一个通道~

时间间隔常量 Duration

time.Duration 是time包定义的一个类型, 代表两个时间点之间经过的时间, 以纳秒为单位

time.Duration 表示1纳秒 time.Second 表示1秒

package main

import (
	"fmt"
	"time"
)

func main() {
	// 定时器: 每隔 xxx s执行一次
	ticker := time.Tick(time.Second) // 这里是每隔1s 执行一次
	for i := range ticker {
		fmt.Println(i)
	}
	// 当然可以对时间进行操作 加减 now.Add() now.Sub() (计算时间的差值)
	// init() 校验时间 -> 当地时间和网络时间是否一致
}