快报:Go 1.16 将会废弃 io/ioutil 包!
其实 20 年 10 月份,Go 掌舵人 Russ Cox 已经有废弃 ioutil 包的提案[1],废弃原因是:
io/ioutil, like most things with util in the name, has turned out to be a poorly defined and hard to understand collection of things.
后续的几次代码提交也证实了这一点,从 Go 1.16 开始会废弃 io/ioutil 包,相关的功能会挪到 io 包或 os 包。
提交记录 io[2]、 os[3]


问题 1:升级 Go 版本有影响吗?
为了便于版本升级,保持兼容性,ioutil 函数依旧会保留,但实际上调用的是 io、os 包里的函数。
可以看下 1.16 版本的代码:
// As of Go 1.16, this function simply calls io.ReadAll.func ReadAll(r io.Reader) ([]byte, error) {return io.ReadAll(r)}// As of Go 1.16, this function simply calls os.ReadFile.func ReadFile(filename string) ([]byte, error) {return os.ReadFile(filename)}
问题 2:如何迁移?
之后如果需要升级到 1.16 版本,迁移代码也很简单,比如 Prometheus 项目中的 wal 包使用了 ioutil 包,就可以这样升级:
package walimport ("fmt""io/ioutil""os"...)func TestLastCheckpoint(t *testing.T) {dir, err := ioutil.TempDir("", "test_checkpoint")require.NoError(t, err)defer func() {require.NoError(t, os.RemoveAll(dir))}()...
只需要将 ioutil.TempDir 改成 os.MkDirTemp。
package walimport ("fmt""os"...)func TestLastCheckpoint(t *testing.T) {dir, err := os.MkDirTemp("", "test_checkpoint")require.NoError(t, err)defer func() {require.NoError(t, os.RemoveAll(dir))}()...
就可以不用导入 ioutil 包。
更多信息可以查看文末 阅读原文。
References
[1] 提案: https://github.com/golang/go/issues/42026[2] io: https://go-review.googlesource.com/c/go/+/263141/[3] os: https://go-review.googlesource.com/c/go/+/266364/
推荐阅读
评论
