在Go语言中,为IO操作添加辅助函数是否是一种不好的实践?

huangapple go评论80阅读模式
英文:

Is it bad practice to add helpers for IO operations in Go?

问题

我来自C#背景,习惯使用System.IO命名空间中的File.ReadAllLinesFile.WriteAllLines等IO方法。但是我有点惊讶地发现Go语言没有这些IO操作的便捷函数。为了避免代码重复,我编写了下面的辅助函数。有没有什么理由不这样做呢?

// WriteBytes将传入的字节写入指定的文件。在写入之前,
// 如果文件已经存在,则删除其所有内容;否则,创建文件。
func WriteBytes(filepath string, bytes []byte) (err error) {
	file, err := os.Create(filepath)
	if err != nil {
		return err
	}
	defer closeWithErrorPropagation(file, &err)

	_, err = file.Write(bytes)
	if err != nil {
		return err
	}

	return err
}

// WriteString将传入的字符串写入指定的文件。在写入之前,
// 如果文件已经存在,则删除其所有内容;否则,创建文件。
func WriteString(filepath string, text string) (err error) {
	file, err := os.Create(filepath)
	if err != nil {
		return err
	}
	defer closeWithErrorPropagation(file, &err)

	_, err = file.WriteString(text)
	if err != nil {
		return err
	}

	return err
}

// WriteLines将传入的行写入指定的文件。在写入之前,
// 如果文件已经存在,则删除其所有内容;否则,创建文件。
func WriteLines(filepath string, lines []string) (err error) {
	file, err := os.Create(filepath)
	if err != nil {
		return err
	}
	defer closeWithErrorPropagation(file, &err)

	for _, line := range lines {
		_, err := file.WriteString(fmt.Sprintln(line))
		if err != nil {
			return err
		}
	}

	return err
}

func closeWithErrorPropagation(c io.Closer, err *error) {
	if closerErr := c.Close(); closerErr != nil && *err == nil { // 仅在没有早期错误时传播关闭器错误。
		*err = closerErr
	}
}
英文:

I come from a C# background and am used IO methods like File.ReadAllLines and File.WriteAllLines from the System.IO namespace. I was a bit surprised to learn that Go didn't have convenience functions for these IO operations. In an effort to avoid code duplication, I wrote the below helpers. Is there any reason to not do this?

// WriteBytes writes the passed in bytes to the specified file. Before writing,
// if the file already exists, deletes all of its content; otherwise, creates
// the file.
func WriteBytes(filepath string, bytes []byte) (err error) {
	file, err := os.Create(filepath)
	if err != nil {
		return err
	}
	defer closeWithErrorPropagation(file, &err)

	_, err = file.Write(bytes)
	if err != nil {
		return err
	}

	return err
}

// WriteString writes the passed in sting to the specified file. Before writing,
// if the file already exists, deletes all of its content; otherwise, creates
// the file.
func WriteString(filepath string, text string) (err error) {
	file, err := os.Create(filepath)
	if err != nil {
		return err
	}
	defer closeWithErrorPropagation(file, &err)

	_, err = file.WriteString(text)
	if err != nil {
		return err
	}

	return err
}

// WriteLines writes the passed in lines to the specified file. Before writing,
// if the file already exists, deletes all of its content; otherwise, creates
// the file.
func WriteLines(filepath string, lines []string) (err error) {
	file, err := os.Create(filepath)
	if err != nil {
		return err
	}
	defer closeWithErrorPropagation(file, &err)

	for _, line := range lines {
		_, err := file.WriteString(fmt.Sprintln(line))
		if err != nil {
			return err
		}
	}

	return err
}

func closeWithErrorPropagation(c io.Closer, err *error) {
	if closerErr := c.Close(); closerErr != nil && *err == nil { // Only propagate the closer error if there isn't already an earlier error.
		*err = closerErr
	}
}

答案1

得分: 4

os.WriteFile 可以处理 WriteBytesWriteString 函数的等效功能:

// func WriteBytes(filepath string, bytes []byte) (err error)

err = os.WriteFile("testdata/hello", []byte("Hello, Gophers!"), 0666)


// func WriteString(filepath string, text string) (err error)

text := "Hello, Gophers!"
err = os.WriteFile("testdata/hello", []byte(text), 0666)

结合 strings.Join,可以处理 WriteLines

//func WriteLines(filepath string, lines []string) (err error)

lines := []string{"hello", "gophers!"}
err = os.WriteFile("testdata/hello", []byte(strings.Join(lines, "\n")), 0666)
英文:

os.WriteFile can handle the equivalent functionality of WriteBytes and WriteString functions:

// func WriteBytes(filepath string, bytes []byte) (err error)
err = os.WriteFile("testdata/hello", []byte("Hello, Gophers!"), 0666)
// func WriteString(filepath string, text string) (err error)
text := "Hello, Gophers!"
err = os.WriteFile("testdata/hello", []byte(text), 0666)

and combined with strings.Join can handle WriteLines:

//func WriteLines(filepath string, lines []string) (err error)
lines := []string{"hello", "gophers!"}
err = os.WriteFile("testdata/hello", []byte(strings.Join(lines, "\n")), 0666)

huangapple
  • 本文由 发表于 2021年10月14日 06:12:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/69562948.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定