首页 > 其他分享 >go io/ioutil 包 1.16后被弃用

go io/ioutil 包 1.16后被弃用

时间:2024-06-06 10:03:18浏览次数:20  
标签:1.16 弃用 err ioutil Go directory io go os

 

来自:

从Golang项目中删除已弃用的ioutil包

 

Go 1.16之前

Go 1.16以前的版本中,如果我们需要开发文件系统、IO等操作,通常会使用到一个名为io/ioutil的包。

目前很多网络上现存的教程文章,我们能够看到这个包的大量应用场景。

Go 1.16及之后版本

自从到了Go 1.16发布以后,io/ioutil就已经被正式弃用。当然,为了兼容性考虑,我们依旧可以正常调用这个包,只不过当我们调用ioutil里面的方法,最后都是跳转到了io以及os包。

你可以尝试将Go版本升级至1.17以上,然后进入io/ioutil包的源码,就可以看到里面只有两个go文件,ioutil.gotempfile.go

附:io/ioutil/ioutil.go源码(Go 1.17+

// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// Package ioutil implements some I/O utility functions.
//
// Deprecated: As of Go 1.16, the same functionality is now provided
// by package io or package os, and those implementations
// should be preferred in new code.
// See the specific function documentation for details.
package ioutil

import (
	"io"
	"io/fs"
	"os"
	"sort"
)

// ReadAll reads from r until an error or EOF and returns the data it read.
// A successful call returns err == nil, not err == EOF. Because ReadAll is
// defined to read from src until EOF, it does not treat an EOF from Read
// as an error to be reported.
//
// Deprecated: As of Go 1.16, this function simply calls io.ReadAll.
func ReadAll(r io.Reader) ([]byte, error) {
	return io.ReadAll(r)
}

// ReadFile reads the file named by filename and returns the contents.
// A successful call returns err == nil, not err == EOF. Because ReadFile
// reads the whole file, it does not treat an EOF from Read as an error
// to be reported.
//
// Deprecated: As of Go 1.16, this function simply calls os.ReadFile.
func ReadFile(filename string) ([]byte, error) {
	return os.ReadFile(filename)
}

// WriteFile writes data to a file named by filename.
// If the file does not exist, WriteFile creates it with permissions perm
// (before umask); otherwise WriteFile truncates it before writing, without changing permissions.
//
// Deprecated: As of Go 1.16, this function simply calls os.WriteFile.
func WriteFile(filename string, data []byte, perm fs.FileMode) error {
	return os.WriteFile(filename, data, perm)
}

// ReadDir reads the directory named by dirname and returns
// a list of fs.FileInfo for the directory's contents,
// sorted by filename. If an error occurs reading the directory,
// ReadDir returns no directory entries along with the error.
//
// Deprecated: As of Go 1.16, os.ReadDir is a more efficient and correct choice:
// it returns a list of fs.DirEntry instead of fs.FileInfo,
// and it returns partial results in the case of an error
// midway through reading a directory.
//
// If you must continue obtaining a list of fs.FileInfo, you still can:
//
//	entries, err := os.ReadDir(dirname)
//	if err != nil { ... }
//	infos := make([]fs.FileInfo, 0, len(entries))
//	for _, entry := range entries {
//		info, err := entry.Info()
//		if err != nil { ... }
//		infos = append(infos, info)
//	}
func ReadDir(dirname string) ([]fs.FileInfo, error) {
	f, err := os.Open(dirname)
	if err != nil {
		return nil, err
	}
	list, err := f.Readdir(-1)
	f.Close()
	if err != nil {
		return nil, err
	}
	sort.Slice(list, func(i, j int) bool { return list[i].Name() < list[j].Name() })
	return list, nil
}

// NopCloser returns a ReadCloser with a no-op Close method wrapping
// the provided Reader r.
//
// Deprecated: As of Go 1.16, this function simply calls io.NopCloser.
func NopCloser(r io.Reader) io.ReadCloser {
	return io.NopCloser(r)
}

// Discard is an io.Writer on which all Write calls succeed
// without doing anything.
//
// Deprecated: As of Go 1.16, this value is simply io.Discard.
var Discard io.Writer = io.Discard

Go 1.17之后(Go 1.17+

从Go 1.17开始,io/ioutil/tempfile.go里面的两个函数TempFileTempDir改为简单地调用os

附:io/ioutil/tempfile.go源码

// Copyright 2010 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package ioutil

import (
	"os"
)

// TempFile creates a new temporary file in the directory dir,
// opens the file for reading and writing, and returns the resulting *os.File.
// The filename is generated by taking pattern and adding a random
// string to the end. If pattern includes a "*", the random string
// replaces the last "*".
// If dir is the empty string, TempFile uses the default directory
// for temporary files (see os.TempDir).
// Multiple programs calling TempFile simultaneously
// will not choose the same file. The caller can use f.Name()
// to find the pathname of the file. It is the caller's responsibility
// to remove the file when no longer needed.
//
// Deprecated: As of Go 1.17, this function simply calls os.CreateTemp.
func TempFile(dir, pattern string) (f *os.File, err error) {
	return os.CreateTemp(dir, pattern)
}

// TempDir creates a new temporary directory in the directory dir.
// The directory name is generated by taking pattern and applying a
// random string to the end. If pattern includes a "*", the random string
// replaces the last "*". TempDir returns the name of the new directory.
// If dir is the empty string, TempDir uses the
// default directory for temporary files (see os.TempDir).
// Multiple programs calling TempDir simultaneously
// will not choose the same directory. It is the caller's responsibility
// to remove the directory when no longer needed.
//
// Deprecated: As of Go 1.17, this function simply calls os.MkdirTemp.
func TempDir(dir, pattern string) (name string, err error) {
	return os.MkdirTemp(dir, pattern)
}

总结

io/ioutil,就像名称中带有 util 的大多数东西一样,已被证明是一个定义不明确且难以理解的东西集合。通常我们不建议在Go项目中使用util作为包名称。

Go1.16之后,官方已经将ioutil下面的所有函数迁移到ioos下面。我们可以在这两个包下面找到新的函数替代以前的ioutil

如果我们曾经在项目中使用了io/ioutil包,那么接下来应该开始使用ioos包了。

相关提案:

https://github.com/golang/go/issues/40025

https://github.com/golang/go/issues/42026

 

参考:https://tehub.com/a/b28Y1oz6AC

标签:1.16,弃用,err,ioutil,Go,directory,io,go,os
From: https://www.cnblogs.com/rebrobot/p/18234507

相关文章

  • Linux 35.5 + JetPack v5.1.3@ ego-planner编译安装
    Linux35.5+JetPackv5.1.3@ego-planner编译安装1.源由2.编译&安装Step1:依赖库安装Step2:建立工程Step3:编译工程Step4:安装工程3.问题汇总3.1planner/plan_env-OpenCV3.2uav_simulator/local_sensing-CUDA优化4.总结1.源由Fast-PlannerFUELRACEReg......
  • goto 语句以及 setjump、longjump 函数的注意事项总结
    关于goto、setjmp、longjmp的注意事项,总结如下:goto语句避免滥用:goto语句虽然能够提供一种直接的跳转方式,但过度使用会使程序结构变得复杂,难以阅读和维护。应优先考虑使用结构化的控制流语句(如if、while、for等)。防止死循环:在使用goto语句时,要特别注意不要形成死......
  • golang 可变参数用法, handlers ...HandlerFunc
     handlers...HandlerFunc这是什么写法,与group.handle()第三个参数是[]handlerFunc是什么关系呢?下面是gin中的用法:routergroup.go//GETisashortcutforrouter.Handle("GET",path,handle).func(group*RouterGroup)GET(relativePathstring,handlers...Ha......
  • 云原生时代:从 Jenkins 到 Argo Workflows,构建高效 CI Pipeline
    作者:蔡靖ArgoWorkflowsArgoWorkflows[1]是用于在Kubernetes上编排Job的开源的云原生工作流引擎。可以轻松自动化和管理Kubernetes上的复杂工作流程。适用于各种场景,包括定时任务、机器学习、ETL和数据分析、模型训练、数据流pipline、CI/CD等。KubernetesJobs......
  • 【Go-多线程】Golang的channel实现消息的批量处理
    【Go-多线程】Golang的channel实现消息的批量处理。当消息量特别大时,使用kafka之类的messagequeue是首选,但这是更加轻量的方案channelx.go//这个方案需要实现以下几点://1.消息聚合后处理(最大条数为BatchSize),核心://(1)带buffer的channel相当于一个FIFO的队列//(2)多个常驻的gorou......
  • go语言方法之封装
        一个对象的变量或者方法如果对调用方是不可见的话,一般就被定义为“封装”。封装有时也叫信息隐藏,同时也是面向对象编程的一个方面。    Go语言只有一种控制可见性的手段:大写首字母的标识符会从定义它们的包中被导出,小写的字母则不会。这种限制包内成员的......
  • Golang初学:一些第三方包
    goversiongo1.22.1-- Web开发gorillahttps://gowebexamples.com中的示例有用到。 Routing(usinggorilla/mux)goget-ugithub.com/gorilla/mux-Sessions"github.com/gorilla/sessions"-Websockets$gogetgithub.com/gorilla/websocket- gingoget......
  • c# MongoDB.Driver 连接mongo 数据库失败的解决方法
    在连接数据库的时候连接本的的时候连接字符串是mongodb://localhost:端口号(默认27017)/数据库名(选填)用这种格式的连接字符串去做本地的测试是没问题的,但是连接服务器上面的数据库的时候就要加上用户名和密码,这个时候就需要在字符串的末尾添加后缀:mongodb://用户名:密码(都不......
  • 2024-06-05:用go语言,给定三个正整数 n、x 和 y, 描述一个城市中由 n 个房屋和 n 条街道
    2024-06-05:用go语言,给定三个正整数n、x和y,描述一个城市中由n个房屋和n条街道连接的情况。城市中存在一条额外的街道连接房屋x和房屋y。需要计算对于每个街道数(从1到n),有多少房屋对满足从一个房屋到另一个房屋经过的街道数正好为该街道数。在结果数组中,索引k对......
  • Exp-Golomb指数哥伦布码
    Exp-Golomb指数哥伦布码指数哥伦布码(Exponential-Golomb)属于熵编码,属于无损编码H.264中使用的是0阶指数哥伦布编码,编码方式如下:以待编码码号code_num=3为例:第一步:将code_num+1,即3+1=4第二步:将4写为二进制的形式:100第三步:计算100的比特个数为3,在100前面写(3-1)个0,得到......