英文:
Can you call gofmt to format a file you've written from inside the Go code that wrote it?
问题
我正在编写输出其他Go代码的Go代码。
我想知道是否有一种方法可以在编写代码的同时调用gofmt工具来格式化我编写的代码。
我找到的关于gofmt的文档,例如官方文档,都是关于如何在命令行中使用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)
// 在这里插入调用gofmt自动格式化myFile.go的代码
}
非常感谢您的时间和智慧。
英文:
I'm writing Go code that outputs other Go code.
I'd like to know if there's a way to call the gofmt tool to format the code I've written from within the code that's done the writing.
The documentation I've found on gofmt, e.g. the official docs, all deals with how to use gofmt from the command line, but I'd like to call it from within Go code itself.
Example:
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
}
Thanks in advance for your time and wisdom.
答案1
得分: 18
go/format
包提供了一个函数来格式化任意文本:
https://golang.org/pkg/go/format/
使用方法很简单:
content, err := format.Source(content)
// 检查错误
file.Write(content)
英文:
The go/format
package makes a function available to format arbitrary text:
https://golang.org/pkg/go/format/
Should be as simple as:
content, err := format.Source(content)
// check error
file.Write(content)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论