标准库¶
strconv¶
Package strconv implements conversions to and from string representations of basic data types.
包 strconv 实现与基本数据类型的字符串表示的转换。
i1, err := strconv.Atoi("-42")
// Itoa (int to string)
s := strconv.Itoa(-42)
// convert strings to values
b, err := strconv.ParseBool("true")
f, err := strconv.ParseFloat("3.1415", 64)
i, err := strconv.ParseInt("-42", 10, 64)
u, err := strconv.ParseUint("42", 10, 64)
// convert values to strings
s1 := strconv.FormatBool(true)
s2 := strconv.FormatFloat(3.1415, 'E', -1, 64)
s3 := strconv.FormatInt(-42, 16)
s4 := strconv.FormatUint(42, 16)
String Conversions¶
Quote and QuoteToASCII convert strings to quoted Go string literals. The latter guarantees that the result is an ASCII string, by escaping any non-ASCII Unicode with \u:
q := strconv.Quote("Hello, 世界")
q := strconv.QuoteToASCII("Hello, 世界")
QuoteRune and QuoteRuneToASCII are similar but accept runes and return quoted Go rune literals.
Unquote and UnquoteChar unquote Go string and rune literals.
sort¶
package main
import (
"fmt"
"sort"
)
type Person struct {
Name string
Age int
}
func (this Person) String() string {
return fmt.Sprintf("%s: %d", this.Name, this.Age)
}
type ByAge []Person
func (a ByAge) Len() int {
return len(a)
}
func (a ByAge) Swap(i, j int) {
a[i], a[j] = a[j], a[i]
}
func (a ByAge) Less(i, j int) bool {
return a[i].Age < a[j].Age
}
func main() {
people := []Person{
{"Bob", 31},
{"John", 42},
{"Michael", 17},
{"Jenny", 26},
}
fmt.Println(people)
// 第一种写法 <
sort.Sort(ByAge(people))
fmt.Println(people)
// 第二种写法 >
sort.Slice(people, func(i, j int) bool {
return people[i].Age > people[j].Age
})
fmt.Println(people)
}
heap¶
Package heap
provides heap operations for any type that implements heap.Interface.
list¶
Package list
implements a doubly linked list.
ring¶
Package ring
implements operations on circular lists.
strings¶
Package strings
implements simple functions to manipulate UTF-8 encoded strings.
bytes¶
Package bytes
implements functions for the manipulation of byte slices.
builtin¶
Package builtin
provides documentation for Go's predeclared identifiers.
bufio¶
Package bufio
implements buffered I/O. It wraps an io.Reader or io.Writer object, creating another object (Reader or Writer) that also implements the interface but provides buffering and some help for textual I/O.
io¶
Package io/fs
defines basic interfaces to a file system.
Package io/ioutil
implements some I/O utility functions.
fmt.Fprintf¶
Go 可以使用 fmt.Sprintf 来格式化字符串,fmt.Sprintf(格式化样式, 参数列表…),格式化样式如下: %v 按值的本来值输出
%+v 在 %v 基础上,对结构体字段名和值进行展开
%#v 输出 Go 语言语法格式的值
%T 输出 Go 语言语法格式的类型和值
%% 输出 % 本体
%b 整型以二进制方式显示
%o 整型以八进制方式显示
%d 整型以十进制方式显示
%x 整型以十六进制方式显示
%X 整型以十六进制、字母大写方式显示
%U Unicode 字符
%f 浮点数
%p 指针,十六进制方式显示