File 使读写器在Go中从/到文件的正确方法

File 使读写器在Go中从/到文件的正确方法,file,go,File,Go,我有这种类型,例如: 类型矩阵[][]int 还有一个这样的文件,保存矩阵数据: Lines: 2 Columns: 3 1 2 3 4 5 6 在Go中保存/加载类似内容的正确方法是什么?如何利用读写器界面?操作系统不是这样的用例吗?我只能这样想: func(m*矩阵)读取(文件名字节[])(n int,err error){ 数据,Util:=ioutil.ReadFile(文件名) //使用split等解析数据并修改“m” 返回len(数据),无 } func(m*矩阵)写入(文件名字

我有这种类型,例如:

类型矩阵[][]int
还有一个这样的文件,保存矩阵数据:

Lines: 2
Columns: 3
1 2 3
4 5 6
在Go中保存/加载类似内容的正确方法是什么?如何利用读写器界面?操作系统不是这样的用例吗?我只能这样想:

func(m*矩阵)读取(文件名字节[])(n int,err error){
数据,Util:=ioutil.ReadFile(文件名)
//使用split等解析数据并修改“m”
返回len(数据),无
}
func(m*矩阵)写入(文件名字节[])(n int,err error){
b:=strings.Builder()
//从“m”中获取数据并填充生成器
ioutil.WriteFile(文件名,b.String(),0666)
返回len(数据),无
}

但这看起来不对,因为我没有利用接口或os.File类型(谁是阅读器),我需要一个已经创建的矩阵实例来填充它。如何正确执行?

io.Reader和io.Writer是字节流上的读写接口。您需要函数对字节流上的矩阵进行编码和解码

使用Matrix包中的io.Reader和io.Writer接口,而不是实现这些接口。将实现留给*os.File,依此类推

读取值时,通常会编写构造函数:

// ReadMatrix creates a new Matrix from the data in r.
func ReadMatrix(r io.Reader) (*Matrix, error) {
  var m Matrix
  data, _ := ioutil.ReadAll(r)
  // Parse data using split, etc and modify "m"
  return &m, nil
}
。。。并有一种写作方法:

// Write writes the contents of the matrix to w.
// Use ReadMatrix to read the data in the format 
// written by Write.
func (m *Matrix) Write(w io.Writer) error {
  bw := bufio.NewWriter(w)
  // Get the data from "m" and write to bw.
  return bw.Flush()
}

io.Reader和io.Writer是字节流上的读写接口。您需要函数对字节流上的矩阵进行编码和解码

使用Matrix包中的io.Reader和io.Writer接口,而不是实现这些接口。将实现留给*os.File,依此类推

读取值时,通常会编写构造函数:

// ReadMatrix creates a new Matrix from the data in r.
func ReadMatrix(r io.Reader) (*Matrix, error) {
  var m Matrix
  data, _ := ioutil.ReadAll(r)
  // Parse data using split, etc and modify "m"
  return &m, nil
}
。。。并有一种写作方法:

// Write writes the contents of the matrix to w.
// Use ReadMatrix to read the data in the format 
// written by Write.
func (m *Matrix) Write(w io.Writer) error {
  bw := bufio.NewWriter(w)
  // Get the data from "m" and write to bw.
  return bw.Flush()
}

如果查看
io.Reader
io.Writer
接口,它们不会将文件名作为参数;因此,虽然这种类型在技术上实现了这些接口,但它的实现方式使其与它们完全不兼容;因此,虽然这种类型在技术上实现了这些接口,但它的实现方式使其与这些接口完全不兼容。