将任意类型的切片写入 Go 中的文件

Gab*_*ter 2 go

出于日志记录的目的,我希望能够快速将任何类型的切片(无论是整数、字符串还是自定义结构)写入 Go 中的文件。例如,在 C# 中,我可以在 1 行中执行以下操作:

File.WriteAllLines(filePath, myCustomTypeList.Select(x => x.ToString());
Run Code Online (Sandbox Code Playgroud)

我将如何在 Go 中做到这一点?结构体实现Stringer接口。

编辑:我特别希望将输出打印到文件中,并且切片中的每个项目打印一行

Cer*_*món 7

使用fmt包格式值作为字符串并打印到文件:

func printLines(filePath string, values []interface{}) error {
    f, err := os.Create(filePath)
    if err != nil {
        return err
    }
    defer f.Close()
    for _, value := range values {
       fmt.Fprintln(f, value)  // print values to f, one per line
    }
    return nil
}
Run Code Online (Sandbox Code Playgroud)

fmt.Fprintln将调用Stringer()您的结构类型。它还将打印int值和string值。

游乐场示例

使用reflect包来编写任意切片类型:

func printLines(filePath string, values interface{}) error {
  f, err := os.Create(filePath)
  if err != nil {
    return err
  }
  defer f.Close()
  rv := reflect.ValueOf(values)
  if rv.Kind() != reflect.Slice {
    return errors.New("Not a slice")
  }
  for i := 0; i < rv.Len(); i++ {
    fmt.Fprintln(f, rv.Index(i).Interface())
  }
  return nil
}
Run Code Online (Sandbox Code Playgroud)

如果你有values类型的变量myCustomList,那么你可以这样调用它:err := printLines(filePath, values)

游乐场示例