【GoLang入门教程】Go语言几种标准库介绍(八)

ChatGPT 和文心一言哪个更好用?

文章目录

    • ChatGPT 和文心一言哪个更好用?
      • 强烈推荐
      • 前言
      • 几种库
        • runtime库 ( 运行时接口)
          • 常用的函数:
          • 示例
        • sort库(排序接口)
          • 主要的函数和接口:
          • 示例
        • strings库(字符串转换、解析及实用函数)
          • 常用的函数:
          • 示例
        • time库(时间接口)
          • 常用的函数:
          • 示例
        • text库(文本模板及 Token 词法器)
          • 1.`text/template` 包:
          • 示例
          • 2.**`text/scanner` 包:**
          • 示例
      • 总结
      • 专栏集锦
      • 强烈推荐
      • 写在最后

579a429daf314744b995f37351b46548

强烈推荐

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

b004071ozy_05_amzn

前言

上一篇,我们介绍了plugin、reflect、regexp三个库,这篇我们继续介绍剩下的库

几种库

runtime库 ( 运行时接口)

在 Go 语言的标准库中,runtime 包提供了与 Go 运行时系统交互的功能。

这个包包括了一些控制和查询运行时状态的函数,如协程控制、垃圾回收、程序退出等。

常用的函数:
  1. Gosched 函数: 让出处理器给其他 goroutine 执行,以便调度器能够有效地分配时间给不同的 goroutine。
  2. Go 函数: 用于启动一个新的 goroutine。
  3. NumCPU 函数: 返回机器上的逻辑 CPU 核心数。
  4. NumGoroutine 函数: 返回当前程序中活跃的 goroutine 数量。
  5. GOMAXPROCS 函数: 用于设置或查询可同时执行的最大 CPU 核心数。
  6. MemStats 结构和 ReadMemStats 函数: 提供了对内存使用情况的统计信息。
示例
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 输出内存统计信息。

sort库(排序接口)

在 Go 语言的标准库中,sort 包提供了对切片和用户定义的集合进行排序的功能。

它支持排序各种类型的数据,包括内置的基本数据类型以及用户定义的类型。

主要的函数和接口:
  1. sort.Interface 接口: 用户定义的类型需要实现这个接口的三个方法(LenLessSwap)来支持排序。这样的类型可以被 sort 包的函数直接使用。
  2. sort.Sort 函数: 对实现了 sort.Interface 接口的类型进行原地排序。
  3. sort.Slice 函数: 对切片进行排序,可以接受切片、比较函数和附加参数。
  4. sort.Search 函数: 在有序切片中查找一个元素,并返回它的索引。如果找不到,返回应该插入的位置。
示例
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.Intssort.Sort 对切片进行排序。

同时,定义了一个 Person 结构体和一个实现了 sort.Interface 接口的 People 类型,然后使用 sort.Sort 对自定义类型的切片进行排序。

最后,使用 sort.Slice 对字符串切片进行排序,并使用 sort.Search 在有序切片中查找元素。

这些函数和接口提供了灵活而强大的排序功能,适用于各种排序需求。

strings库(字符串转换、解析及实用函数)

在 Go 语言的标准库中,strings 包提供了对字符串进行操作的各种函数。

这些函数包括字符串的拼接、切割、替换、搜索等,提供了丰富的字符串处理功能。

常用的函数:
  1. Contains 函数: 判断字符串是否包含子串。
  2. Count 函数: 统计子串在字符串中出现的次数。
  3. HasPrefixHasSuffix 函数: 判断字符串是否以指定的前缀或后缀开始或结束。
  4. IndexLastIndex 函数: 返回子串在字符串中第一次和最后一次出现的位置。
  5. Join 函数: 将字符串切片连接成一个字符串,中间用指定的分隔符分隔。
  6. Replace 函数: 替换字符串中的指定子串。
  7. Split 函数: 将字符串切割成字符串切片,根据指定的分隔符。
  8. ToLowerToUpper 函数: 将字符串转换为小写或大写。
示例
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
}

这些函数提供了丰富的字符串处理功能,可以满足各种字符串操作的需求。

time库(时间接口)

在 Go 语言的标准库中,time 包提供了对时间的处理和操作功能。

time 包主要包含了表示时间的结构体、时间的格式化和解析、定时器等相关的功能。

常用的函数:
  1. Time 类型: 表示一个具体的时间点。Time 类型的值可以通过 time.Now() 获取当前时间,也可以通过 time.Parse 解析字符串得到。
  2. Duration 类型: 表示时间间隔,用于表示两个 Time 值之间的差异。
  3. time.Now 函数: 获取当前时间。
  4. time.Aftertime.Sleep 函数: 用于等待一段时间。
  5. time.Parsetime.Format 函数: 用于时间格式的解析和格式化。
  6. time.Timertime.Ticker 类型: 分别表示定时器和周期性的定时器。
示例
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 创建周期性的定时器等。

text库(文本模板及 Token 词法器)

在 Go 语言的标准库中,“text” 包并不存在。

只有一些与文本处理相关的包,比如 text/templatetext/scanner

1.text/template 包:

提供了一种简单的模板引擎,用于生成文本输出。它允许在模板中嵌入变量和控制结构,然后通过传入数据来生成最终的文本输出。

示例
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)
}
2.text/scanner 包:

提供了一个用于扫描文本的基本扫描器。这个包可用于将文本分割成令牌(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

强烈推荐

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

b004071ozy_05_amzn

写在最后

感谢您的支持和鼓励! 😊🙏

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

csdn-end

版权声明:本文为博主作者:The-Venus原创文章,版权归属原作者,如果侵权,请联系我们删除!

原文链接:https://blog.csdn.net/jinxinxin1314/article/details/135662764

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
心中带点小风骚的头像心中带点小风骚普通用户
上一篇 2024年2月19日
下一篇 2024年2月19日

相关推荐