前些天发现了一个巨牛的人工智能学习网站,通俗易懂,风趣幽默,忍不住分享一下给大家。点击跳转到网站:人工智能

上一篇,我们介绍了plugin、reflect、regexp三个库,这篇我们继续介绍剩下的库
在 Go 语言的标准库中,runtime 包提供了与 Go 运行时系统交互的功能。
这个包包括了一些控制和查询运行时状态的函数,如协程控制、垃圾回收、程序退出等。
package main
import (
"fmt"
"runtime"
"sync"
)
func main() {
// 设置最大同时执行的 CPU 核心数
runtime.GOMAXPROCS(2)
// 获取机器上的逻辑 CPU 核心数
numCPU := runtime.NumCPU()
fmt.Println("Number of CPUs:", numCPU)
// 启动多个 goroutine
var wg sync.WaitGroup
for i := 0; i < 5; i++ {
wg.Add(1)
go func(index int) {
defer wg.Done()
fmt.Printf("Goroutine %d is running on CPU %d\n", index, runtime.NumCPU())
}(i)
}
wg.Wait()
// 获取当前程序中活跃的 goroutine 数量
numGoroutines := runtime.NumGoroutine()
fmt.Println("Number of Goroutines:", numGoroutines)
// 让出处理器给其他 goroutine 执行
runtime.Gosched()
// 输出内存统计信息
var memStats runtime.MemStats
runtime.ReadMemStats(&memStats)
fmt.Printf("Allocated memory: %d bytes\n", memStats.Alloc)
fmt.Printf("Total memory allocated: %d bytes\n", memStats.TotalAlloc)
fmt.Printf("Heap memory allocated: %d bytes\n", memStats.HeapAlloc)
}
在这个示例中,使用了 runtime.GOMAXPROCS 设置最大同时执行的 CPU 核心数,使用 runtime.NumCPU 获取机器上的逻辑 CPU 核心数,使用 runtime.NumGoroutine 获取当前程序中活跃的 goroutine 数量。
还启动了多个 goroutine 并使用 runtime.Gosched 让出处理器给其他 goroutine 执行。最后,使用 runtime.ReadMemStats 输出内存统计信息。
在 Go 语言的标准库中,sort 包提供了对切片和用户定义的集合进行排序的功能。
它支持排序各种类型的数据,包括内置的基本数据类型以及用户定义的类型。
package main
import (
"fmt"
"sort"
)
// 定义一个结构体类型
type Person struct {
Name string
Age int
}
// 定义一个实现 sort.Interface 接口的切片类型
type People []Person
func (p People) Len() int { return len(p) }
func (p People) Less(i, j int) bool { return p[i].Age < p[j].Age }
func (p People) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
func main() {
// 基本数据类型的切片排序
intSlice := []int{5, 2, 7, 1, 8, 3}
sort.Ints(intSlice)
fmt.Println("Sorted Ints:", intSlice)
// 自定义类型的切片排序
people := People{
{"Alice", 25},
{"Bob", 30},
{"Charlie", 22},
}
sort.Sort(people)
fmt.Println("Sorted People:", people)
// 使用 sort.Slice 对切片进行排序
strSlice := []string{"banana", "apple", "orange", "grape"}
sort.Slice(strSlice, func(i, j int) bool {
return len(strSlice[i]) < len(strSlice[j])
})
fmt.Println("Sorted Strings by Length:", strSlice)
// 使用 sort.Search 在有序切片中查找元素
searchSlice := []int{1, 2, 3, 4, 5, 6, 7, 8, 9}
index := sort.Search(len(searchSlice), func(i int) bool {
return searchSlice[i] >= 6
})
fmt.Println("Index of 6 in Sorted Slice:", index)
}
在这个示例中,使用了 sort.Ints 和 sort.Sort 对切片进行排序。
同时,定义了一个 Person 结构体和一个实现了 sort.Interface 接口的 People 类型,然后使用 sort.Sort 对自定义类型的切片进行排序。
最后,使用 sort.Slice 对字符串切片进行排序,并使用 sort.Search 在有序切片中查找元素。
这些函数和接口提供了灵活而强大的排序功能,适用于各种排序需求。
在 Go 语言的标准库中,strings 包提供了对字符串进行操作的各种函数。
这些函数包括字符串的拼接、切割、替换、搜索等,提供了丰富的字符串处理功能。
package main
import (
"fmt"
"strings"
)
func main() {
// Contains函数:判断字符串是否包含子串
fmt.Println(strings.Contains("Hello, Gophers!", "Go")) // true
// Count函数:统计子串在字符串中出现的次数
fmt.Println(strings.Count("banana", "a")) // 3
// HasPrefix和HasSuffix函数:判断字符串是否以指定的前缀或后缀开始或结束
fmt.Println(strings.HasPrefix("Gopher", "Go")) // true
fmt.Println(strings.HasSuffix("Gopher", "per")) // true
// Index和LastIndex函数:返回子串在字符串中第一次和最后一次出现的位置
fmt.Println(strings.Index("Hello, Gophers!", "Gophers")) // 7
fmt.Println(strings.LastIndex("Hello, Gophers!", "o")) // 10
// Join函数:将字符串切片连接成一个字符串,中间用指定的分隔符分隔
strSlice := []string{"apple", "banana", "orange"}
joinedString := strings.Join(strSlice, ", ")
fmt.Println(joinedString) // apple, banana, orange
// Replace函数:替换字符串中的指定子串
replacedString := strings.Replace("Hello, Gophers!", "Gophers", "World", -1)
fmt.Println(replacedString) // Hello, World!
// Split函数:将字符串切割成字符串切片,根据指定的分隔符
splitString := strings.Split("apple,banana,orange", ",")
fmt.Println(splitString) // [apple banana orange]
// ToLower和ToUpper函数:将字符串转换为小写或大写
lowerString := strings.ToLower("GoLang")
upperString := strings.ToUpper("GoLang")
fmt.Println(lowerString, upperString) // golang GOLANG
}
这些函数提供了丰富的字符串处理功能,可以满足各种字符串操作的需求。
在 Go 语言的标准库中,time 包提供了对时间的处理和操作功能。
time 包主要包含了表示时间的结构体、时间的格式化和解析、定时器等相关的功能。
package main
import (
"fmt"
"time"
)
func main() {
// 获取当前时间
now := time.Now()
fmt.Println("Current Time:", now)
// 格式化时间
fmt.Println("Formatted Time:", now.Format("2006-01-02 15:04:05"))
// 解析时间字符串
parsedTime, err := time.Parse("2006-01-02", "2023-01-01")
if err != nil {
fmt.Println("Error parsing time:", err)
return
}
fmt.Println("Parsed Time:", parsedTime)
// 时间间隔(Duration)
duration := 3 * time.Second
fmt.Println("Duration:", duration)
// 等待一段时间
time.Sleep(2 * time.Second)
fmt.Println("After Sleep")
// 定时器
timer := time.NewTimer(1 * time.Second)
<-timer.C
fmt.Println("Timer expired")
// 周期性定时器
ticker := time.NewTicker(500 * time.Millisecond)
for i := 0; i < 5; i++ {
<-ticker.C
fmt.Println("Ticker Tick", i+1)
}
ticker.Stop()
fmt.Println("Ticker stopped")
}
在这个示例中,使用 time.Now 获取当前时间,使用 Format 格式化时间,使用 time.Parse 解析时间字符串,使用 time.Sleep 等待一段时间,使用 time.NewTimer 创建定时器,使用 time.NewTicker 创建周期性的定时器等。
在 Go 语言的标准库中,“text” 包并不存在。
只有一些与文本处理相关的包,比如 text/template 或 text/scanner。
提供了一种简单的模板引擎,用于生成文本输出。它允许在模板中嵌入变量和控制结构,然后通过传入数据来生成最终的文本输出。
package main
import (
"os"
"text/template"
)
func main() {
// 定义模板
tpl := "Hello, {{.Name}}! Today is {{.Day}}."
// 创建模板对象
t := template.Must(template.New("greeting").Parse(tpl))
// 准备数据
data := map[string]interface{}{
"Name": "Gopher",
"Day": "Wednesday",
}
// 渲染模板
t.Execute(os.Stdout, data)
}
提供了一个用于扫描文本的基本扫描器。这个包可用于将文本分割成令牌(Token)并对其进行处理。
package main
import (
"fmt"
"strings"
"text/scanner"
)
func main() {
// 创建扫描器
var s scanner.Scanner
s.Init(strings.NewReader("Hello, World!"))
// 扫描并打印令牌
for tok := s.Scan(); tok != scanner.EOF; tok = s.Scan() {
fmt.Printf("Token: %s\n", s.TokenText())
}
}
这里我们介绍了5个库runtime、sort、strings、time、text ,至此,所有的标准库都已经介绍完了
大佬们可以收藏以备不时之需:
Spring Boot 专栏:http://t.csdnimg.cn/peKde
ChatGPT 专栏:http://t.csdnimg.cn/cU0na
Java 专栏:http://t.csdnimg.cn/YUz5e
Go 专栏:http://t.csdnimg.cn/Jfryo
Netty 专栏:http://t.csdnimg.cn/0Mp1H
Redis 专栏:http://t.csdnimg.cn/JuTue
Mysql 专栏:http://t.csdnimg.cn/p1zU9
架构之路 专栏:http://t.csdnimg.cn/bXAPS
前些天发现了一个巨牛的人工智能学习网站,通俗易懂,风趣幽默,忍不住分享一下给大家。点击跳转到网站:人工智能

感谢您的支持和鼓励! 😊🙏
如果大家对相关文章感兴趣,可以关注公众号"架构殿堂",会持续更新AIGC,java基础面试题, netty, spring boot, spring cloud, Go,python等系列文章,一系列干货随时送达!

上一篇:spark-udf函数