Golang | 内置库常用函数
排序相关
import "sort"
// 升序:
intList := []int{2, 3, 1, 4, 56, 2}
sort.Ints(intList) // [1, 2, 2, 3, 4, 56]
// 降序
sort.Sort(sort.Reverse(sort.IntSlice(intList))) // [56, 4, 3, 2, 2, 1]
// 自定义排序
type Node struct {
val int
}
nodes := make([]Node, 0)
sort.Slice(nodes, func(i, j int) bool {
return nodes[i].val < nodes[j].val
})
类型转换相关
import "strconv"
----------string和int---------------
// string to int
int, err := strconv.Atoi(string)
// int to string
string := strconv.Itoa(int)
----------string和int64---------------
// int64 to string 10进制
string := strconv.FormatInt(int64, 10)
// string to int64 10进制(base),64位(bitsize)
int64, err := strconv.ParseInt(string, 10, 64)
----------string和float64---------------
// float64 to string f表示十进制,1表示保留一位小数
string := strconv.FormatFloat(float64, 'f', 1, 64)
字符串相关
import "strings"
// 1、分割 返回 []string
str := "a,b,c"
strSlice := strings.Split(str, ",") // ["a", "b", "c"]
// 2、将字符串数组合并成一个字符串
str = strings.Join(strSlice, ":") // "a:b:c"
// 3、去掉首尾空格
str := strings.TrimSpace(str)
// 4、自定义分割函数
f := func(c rune) bool {
return c == ',' || c == ' ' || c == '?' || c == '!'
}
// 返回 []string
words := strings.FieldsFunc(str, f)
// 5、判断字符串是否包含子串, 参数均是string类型
strings.Contains(str, substr)
result := &strings.Builder{}
result.WriteByte(byte(j) + '0')
result.WriteByte(word[i])
result.String()
json相关
import "encoding/json"
// 序列化结构体,返回 []byte
buf, err := json.Marshall(struct)
// 解析 []byte 到结构体中
err := json.UnMarshal(buf, &struct)
时间相关
import "time"
// 将string转化为 time.Time 类型
t, _ := time.Parse("20060102", string) // 这种方式实际上会多八个小时 默认使用的是UTC
t, _ :- time.ParseInLocation("8:00:00", strTime, time.Local) // 使用这个指定本地时区
// 对时间 转化为 自己想要的格式(string)
formatTime := t.Format("2006.01.02 15:04:05")
// 精确到毫秒
time.Now().Format("2006-01-02 15:04:05.000")
// 将时间转化为时间戳(int64)
t := time.Unix()
// 获取当前时间的年月日
year, month, day := time.Now().Date()
// 判断t1是否在t2之后,是返回true
t1.After(t2)
// 判断t1是否在t3之前,是返回true
t1.Before(t3)
// 创建一个自定义日期
startTime = time.Date(2016, 6, 1, 0, 0, 0, 0, time.Local)
反射相关
import "reflect"
// 获取变量的类型
tp := reflect.TypeOf(funType)
param := tp.In(idx).Name() //获取函数的参数值
Mysql 相关
// 创建记录-增
db.Table().Create(&record)
// 查找记录-查
db.Table().Find(&res, where, value)
// 更新记录-改
db.Table().Find(&res, where, value).Update("xxx", val)
// 删除记录-删
db.Table().Where(query, value).Delete(&res)
Redis 相关
// 获取信息
userInfoMap, err := redis.RedisClient.HGetAll(ctx, key)
// 更新信息 subKV 为 map[string]interface{}
_, err := redis.RedisClient.HMSet(ctx, key, subKV)
// 删除信息
_, err := redis.RedisClient.Del(ctx, key)
slices相关
import "slices"
// 求切片中最大和最小的数
slices.Max(arr)
slices.Min(arr)
// 判断两个切片是否相等
slices.Equal(arr1, arr2)
Rand 相关
import "math/rand"
// 生成[min,max)随机值
seed := rand.New(rand.NewSource(time.Now().UnixNano()))
seed.Intn(max-min) + min
math 相关
import "math"
// 最大和最小值
math.MaxInt64
math.MinInt64
//-----以下函数的参数和返回值均为 float64-------
// x的绝对值
math.Abs(x)
// x开根号
math.Sqrt(x)
// x四舍五入
math.Round(x)
// x向下取整
math.Floor(x)
// x向上取整
math.Ceil(x)
// 返回x的整数部分
math.Trunc(x)
// 返回x的整数和小数部分,返回int和float64
int, float64 := math.Modf(x)
// x的y次方
math.Pow(x, y)
// 10的x次方,x为int, 返回float64
math.Pow10(x)
atomic相关
import "sync/atomic"
// 存储复杂的数据结构
var test atomic.Value
// v 可以是结构体,map等所有类型
test.Store(v)
// Load出来之后 通过v的类型就行断言
test.Load().map[int]int
加解密相关
//1、base64 加密
import "encoding/base64"
// 加密, 参数是 []byte, 返回string
encodedStr := base64.StdEncoding.EncodeToString([]byte("hello"))
// 解密,参数是 string, 返回 []byte
decodeData, err := base64.StdEncoding.DecodeString(encodedStr)
decodeStr := string(decodeData)
//2、md5加密,不可逆
import (
"crypto/md5"
"encoding/hex"
}
h := md5.New()
h.Write([]byte("hello"))
decodedStr := hex.EncodeToString(h.Sum(nil))
正则表达式相关
import "regexp"
// 匹配所有的邮箱
pattern := `\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b`
re := regexp.MustCompile(pattern)
matches := re.FindAllString(str, -1)
评论区