Skip to content

add the features of Go 1.16 #83

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions chapter01/01.2.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

说明:这些函数使用都相对简单,一般就不举例子了。

Go1.16在io包和os包中提供了相同的函数,新代码应该使用这些实现。

## NopCloser 函数 ##

有时候我们需要传递一个 io.ReadCloser 的实例,而我们现在有一个 io.Reader 的实例,比如:strings.Reader ,这个时候 NopCloser 就派上用场了。它包装一个io.Reader,返回一个 io.ReadCloser ,而相应的 Close 方法啥也不做,只是返回 nil。
Expand All @@ -17,6 +19,8 @@
```
如果没有这个函数,我们得自己实现一个。当然,实现起来很简单,读者可以看看 [NopCloser](http://docscn.studygolang.com/src/io/ioutil/ioutil.go?s=5557:5598#L145) 的实现。

在Go1.16中,该函数为io.NopCloser。

## ReadAll 函数 ##

很多时候,我们需要一次性读取 io.Reader 中的数据,通过上一节的讲解,我们知道有很多种实现方式。考虑到读取所有数据的需求比较多,Go 提供了 ReadAll 这个函数,用来从io.Reader 中一次读取所有数据。
Expand All @@ -25,6 +29,8 @@
```
阅读该函数的源码发现,它是通过 bytes.Buffer 中的 [ReadFrom](http://docscn.studygolang.com/src/bytes/buffer.go?s=5385:5444#L144) 来实现读取所有数据的。该函数成功调用后会返回 err == nil 而不是 err == EOF。(成功读取完毕应该为 err == io.EOF,这里返回 nil 由于该函数成功期望 err == io.EOF,符合无错误不处理的理念)

在Go1.16中,该函数为io.ReadAll。

## ReadDir 函数 ##

笔试题:编写程序输出某目录下的所有文件(包括子目录)
Expand Down Expand Up @@ -62,6 +68,8 @@ func listAll(path string, curHier int){
}
```

在Go 1.16中,os.ReadDir是一个更高效和正确的选择:它返回fs.DirEntry列表,而不是fs.FileInfo。如果在读取目录中途发生错误,它返回部分结果。

## ReadFile 和 WriteFile 函数 ##

ReadFile 读取整个文件的内容,在上一节我们自己实现了一个函数读取文件整个内容,由于这种需求很常见,因此 Go 提供了 ReadFile 函数,方便使用。ReadFile 的实现和ReadAll 类似,不过,ReadFile 会先判断文件的大小,给 bytes.Buffer 一个预定义容量,避免额外分配内存。
Expand All @@ -74,6 +82,8 @@ ReadFile 函数的签名如下:

> ReadFile 从 filename 指定的文件中读取数据并返回文件的内容。成功的调用返回的err 为 nil 而非 EOF。因为本函数定义为读取整个文件,它不会将读取返回的 EOF 视为应报告的错误。(同 ReadAll )

在Go 1.16中,该函数为os.ReadFile。

WriteFile 函数的签名如下:
```go
func WriteFile(filename string, data []byte, perm os.FileMode) error
Expand All @@ -82,6 +92,8 @@ WriteFile 函数的签名如下:

> WriteFile 将data写入filename文件中,当文件不存在时会根据perm指定的权限进行创建一个,文件存在时会先清空文件内容。对于 perm 参数,我们一般可以指定为:0666,具体含义 os 包中讲解。

在Go 1.16中,该函数为os.WriteFile。

**小提示**

ReadFile 源码中先获取了文件的大小,当大小 < 1e9 时,才会用到文件的大小。按源码中注释的说法是 FileInfo 不会很精确地得到文件大小。
Expand Down Expand Up @@ -119,6 +131,8 @@ devNull 在实现 io.Writer 接口时,只是简单的返回(标准库文件
```
而 ReadFrom 的实现是读取内容到一个 buf 中,最大也就 8192 字节,其他的会丢弃(当然,这个也不会读取)。

在Go 1.16中,干脆就是io.Discard。

# 导航 #

- [目录](/preface.md)
Expand Down