drvkf88226 2016-12-05 04:49
浏览 91

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

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条回答 默认 最新

  • duanjie5570 2016-12-05 05:34
    关注

    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("Not a slice")
      }
      for i := 0; i < 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

    评论

报告相同问题?

悬赏问题

  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥50 我撰写的python爬虫爬不了 要爬的网址有反爬机制
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据