gpt4 book ai didi

go - 你能调用 gofmt 来格式化你从编写它的 Go 代码内部编写的文件吗?

转载 作者:IT王子 更新时间:2023-10-29 01:21:08 27 4
gpt4 key购买 nike

我正在编写输出其他 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/format 包提供了一个函数来格式化任意文本:

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

应该像这样简单:

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

关于go - 你能调用 gofmt 来格式化你从编写它的 Go 代码内部编写的文件吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45616552/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com