Write a slice of any type to a file in Go

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

Write a slice of any type to a file in Go

问题

为了记录目的,我想要能够快速地将任何类型的切片(包括整数、字符串或自定义结构体)写入到Go语言的文件中。例如,在C#中,我可以用一行代码实现以下功能:

File.WriteAllLines(filePath, myCustomTypeList.Select(x => x.ToString());

在Go语言中,我该如何实现这个功能呢?这些结构体实现了Stringer接口。

编辑:我特别希望将输出打印到一个文件中,每个切片项占据一行。

英文:

For logging purposes I want to be able to quickly write a slice of any type, whether it be ints, strings, or custom structs, to a file in Go. For instance, in C#, I can do the following in 1 line:

File.WriteAllLines(filePath, myCustomTypeList.Select(x => x.ToString());

How would I go about doing this in Go? The structs implement the Stringer interface.

Edit: I in particular would like the output to be printed to a file and one line per item in the slice

答案1

得分: 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)  // 将值逐行打印到文件 f 中
    }
    return nil
}

fmt.Fprintln 会调用你的结构体类型上的 Stringer() 方法。它也可以打印 int 值和 string 值。

playground 示例

使用 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
}

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

playground 示例

英文:

Use the fmt package format values as strings and print to a file:

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
}

fmt.Fprintln will call Stringer() on your struct type. It will also print int values and string values.

playground example

Use the reflect package to write any slice type:

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(&quot;Not a slice&quot;)
  }
  for i := 0; i &lt; rv.Len(); i++ {
	fmt.Fprintln(f, rv.Index(i).Interface())
  }
  return nil
}

If you have variable values of type myCustomList, then you can call it like this: err := printLines(filePath, values)

playground example

huangapple
  • 本文由 发表于 2016年12月5日 12:49:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/40967282.html
匿名

发表评论

匿名网友

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

确定