【问题标题】:Can you call gofmt to format a file you've written from inside the Go code that wrote it?您可以调用 gofmt 来格式化您从编写它的 Go 代码中编写的文件吗?
【发布时间】:2017-08-10 14:30:04
【问题描述】:

我正在编写输出其他 Go 代码的 Go 代码。

我想知道是否有一种方法可以调用 gofmt 工具来格式化我在完成编写的代码中编写的代码。

我在 gofmt 上找到的文档,例如the official docs,所有内容都涉及如何从命令行使用 gofmt,但我想从 Go 代码本身中调用它。

例子:

func WriteToFile(content string) {
    file, err := os.Create("../output/myFile.go")
    if err != nil {
        log.Fatal("Cannot create file", err)
    }
    defer file.Close()
    fmt.Fprint(file, content)
    //Insert code to call gofmt to automatically format myFile.go here
}

提前感谢您的时间和智慧。

【问题讨论】:

    标签: go gofmt


    【解决方案1】:

    go/format 包提供了一个函数来格式化任意文本:

    https://golang.org/pkg/go/format/

    应该很简单:

    content, err := format.Source(content)
    // check error
    file.Write(content)
    

    【讨论】:

      猜你喜欢
      • 2018-09-02
      • 1970-01-01
      • 1970-01-01
      • 2021-12-09
      • 1970-01-01
      • 1970-01-01
      • 2023-03-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多