快報(bào):Go 1.16 將會(huì)廢棄 io/ioutil 包!
其實(shí) 20 年 10 月份,Go 掌舵人 Russ Cox 已經(jīng)有廢棄 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.
后續(xù)的幾次代碼提交也證實(shí)了這一點(diǎn),從 Go 1.16 開始會(huì)廢棄 io/ioutil 包,相關(guān)的功能會(huì)挪到 io 包或 os 包。
提交記錄?io[2]、?os[3]


問(wèn)題 1:升級(jí) Go 版本有影響嗎?
為了便于版本升級(jí),保持兼容性,ioutil 函數(shù)依舊會(huì)保留,但實(shí)際上調(diào)用的是 io、os 包里的函數(shù)。
可以看下 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)}
問(wèn)題 2:如何遷移?
之后如果需要升級(jí)到 1.16 版本,遷移代碼也很簡(jiǎn)單,比如 Prometheus 項(xiàng)目中的 wal 包使用了 ioutil 包,就可以這樣升級(jí):
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))}()...
就可以不用導(dǎo)入 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/
推薦閱讀
