1. fmt 包
fmt 包的介绍:fmt = format,是一种格式化输出函数汇总包,用于格式化输出。
Println、Print、Printf
fmt.Print 原样输出
Print formats using the default formats for its operands and writes to standard output.
start := time.Now()
fmt.Print(start)
// 2023-01-12 16:50:00.2675807 +0800 CST m=+0.002138901
fmt.Printf 格式输出
Printf formats according to a format specifier and writes to standard output.
根据格式打印输出,Printf = Print format 使用方法:
fmt.Printf("%格式1 %格式2", 变量值1, 变量2)
格式占位符类型:%s
: 字符串、%d
: 10进制数值、%T
: type(值)
fmt.Println 值 + 空格 输出
Println formats using the default formats for its operands and writes to standard output. Spaces are always added between operands and a newline is appended.
const name, age = "Kim", 22
fmt.Println(name, age)
2. time 包
Package time provides functionality for measuring and displaying time.
The calendrical calculations always assume a Gregorian calendar, with no leap seconds.
历法计算总是采用公历,没有闰秒。
Operating systems provide both a “wall clock,” which is subject to changes for clock synchronization, and a “monotonic clock,” which is not. The general rule is that the wall clock is for telling time and the monotonic clock is for measuring time. Rather than split the API, in this package the Time returned by time.Now contains both a wall clock reading and a monotonic clock reading; later time-telling operations use the wall clock reading, but later time-measuring operations, specifically comparisons and subtractions, use the monotonic clock reading.
操作系统提供了一个“挂钟”和一个“单调钟”,前者会因为时钟同步而发生变化,后者则不会。一般的规则是挂钟是用来报时的,单调钟是用来测量时间的。在这个包中,Time按时间返回,而不是拆分API。现在包含一个挂钟读数和一个单调时钟读数;后来的报时操作使用挂钟读数,但后来的时间测量操作,特别是比较和减法,使用单调的时钟读数。
func Sleep 暂停时间
Sleep pauses the current goroutine for at least the duration d. A negative or zero duration causes Sleep to return immediately.
Sleep将当前的gorroutine暂停至少持续时间d。持续时间为负值或零将导致Sleep立即返回。
func Sleep(d Duration)
Sleep 案例展示:
var timer int = 0
for i := 0; i < 100; i++ {
fmt.Printf("now timer is %d items \n", timer)
time.Sleep(1000 * time.Millisecond)
timer++
}
func ParseDuration 解析持续时间字符串
ParseDuration parses a duration string. A duration string is a possibly signed sequence of decimal numbers, each with optional fraction and a unit suffix, such as “300ms”, “-1.5h” or “2h45m”. Valid time units are “ns”, “us” (or “µs”), “ms”, “s”, “m”, “h”.
ParseDuration解析持续时间字符串。持续时间字符串是可能的十进制数字符号序列,每个序列都有可选的分数和单位后缀,例如“300ms”、“-1.5h”或“2h45m”。
duration, err := time.ParseDuration("1h20m30s")
fmt.Printf("err value is : %T", err)
// err value is : err
fmt.Println("Hour time is ", duration.Hours())
// Hour time is 1.3416666666666668
func AfterFunc(d Duration, f func()) *Timer
AfterFunc waits for the duration to elapse and then calls f in its own goroutine. It returns a Timer that can be used to cancel the call using its Stop method.
定时器不管是业务开发,还是基础架构开发,都是绕不过去的存在,由此可见定时器的重要程度。
我们不管用 NewTimer, timer.After,还是 timer.AfterFun 来初始化一个 timer, 这个 timer 最终都会加入到一个全局 timer 堆中,由 Go runtime 统一管理。
3. os 包
Package os provides a platform-independent interface to operating system functionality. The design is Unix-like, although the error handling is Go-like; failing calls return values of type error rather than error numbers. Often, more information is available within the error. For example, if a call that takes a file name fails, such as Open or Stat, the error will include the failing file name when printed and will be of type *PathError, which may be unpacked for more information.
The os interface is intended to be uniform across all operating systems. Features not generally available appear in the system-specific package syscall.
WriteString 写入字符串
使用 os 包进行文件写入操作,代码展示:
file, err := os.OpenFile("helloworld.txt", syscall.O_RDWR|syscall.O_CREAT, 0)
if err != nil {
os.Exit(1)
}
defer file.Close()
file.WriteString("hello world. Nice to see you.")
If the open fails, the error string will be self-explanatory, like
open file.go: no such file or directory
os.FileMode(0600) 文件权限:windows系统权限失效。
Fatal is equivalent to Print() followed by a call to os.Exit(1).
Fatal等价于Print()之后调用os.Exit(1)。
Exactly one of O_RDONLY, O_WRONLY, or O_RDWR must be specified.
O_RDONLY int = syscall.O_RDONLY // open the file read-only.
O_WRONLY int = syscall.O_WRONLY // open the file write-only.
O_RDWR int = syscall.O_RDWR // open the file read-write.
The remaining values may be or’ed in to control behavior.
O_APPEND int = syscall.O_APPEND // append data to the file when writing.
O_CREATE int = syscall.O_CREAT // create a new file if none exists.
O_EXCL int = syscall.O_EXCL // used with O_CREATE, file must not exist.
O_SYNC int = syscall.O_SYNC // open for synchronous I/O.
O_TRUNC int = syscall.O_TRUNC // truncate regular writable file when opened.
Read 读取数据
The file’s data can then be read into a slice of bytes. Read and Write take their byte counts from the length of the argument slice.
data := make([]byte, 100)
count, err := file.Read(data)
if err != nil {
log.Fatal(err)
}
fmt.Printf("read %d bytes: %q\n", count, data[:count])
defer 语句
go语言中的defer语句会将其后面跟随的语句进行延迟处理。在defer归属的函数即将返回时,将延迟处理的语句按defer定义的逆序进行执行,也就是说,先被defer的语句最后被执行,最后被defer的语句,最先被执行。
defer一般用于资源的释放和异常的捕捉, 作为Go语言的特性之一。
defer 语句会将其后面跟随的语句进行延迟处理。意思就是说 跟在defer后面的语言 将会在程序进行最后的return之后再执行.
在 defer 归属的函数即将返回时,将延迟处理的语句按 defer 的逆序进行执行,也就是说,先被 defer 的语句最后被执行,最后被 defer 的语句,最先被执行。