英文:
Does my gofmt work wrongly or I don't understand something?
问题
我猜我的gofmt
工作不像它应该的那样,我是对的吗?
原始文件:
package main
import "fmt"
func main() {
fmt.Printf("hello, world\n")
}
然后我执行了:
gofmt -r 'h -> H' -w "hello.go"
之后文件的内容:
package H
import "fmt"
func H() {
H
}
英文:
I suppose that my gofmt
works not how it's supposed to, am I right ?
Original file:
package main
import "fmt"
func main() {
fmt.Printf("hello, world\n")
}
Then I did:
gofmt -r 'h -> H' -w "hello.go"
Content of the file after:
package H
import "fmt"
func H() {
H
}
答案1
得分: 5
据我理解,gofmt
的工作方式与其作者预期的可能不同于你的期望。
文档中提到:
> 模式和替换都必须是有效的Go表达式。在模式中,单个小写字母标识符用作通配符,匹配任意子表达式;这些表达式将被替换为替换中的相同标识符。
由于模式中只有一个小写字母,它匹配所有子表达式,然后用H
替换它们。让我们进一步看一个例子,考虑以下代码:
package main
import "fmt"
func compare(a, b int) {
if a + b < a * b {
fmt.Printf("hello, world\n")
}
}
经过相同的gofmt
命令后,上述代码变成了:
package H
import "fmt"
func H(H, H H) {
if H+H < H*H {
H
}
}
如果这不是你想要的结果,那么你应该使用更具体的模式表达式。
英文:
Presumably gofmt
works as its authors intended, which might be different from what you expected.
The documentation says:
> Both pattern and replacement must be valid Go expressions. In the pattern, single-character lowercase identifiers serve as wildcards matching arbitrary sub-expressions; those expressions will be substituted for the same identifiers in the replacement.
As you have only a single lowercase letter in the pattern, it matches all sub-expressions. And then replaces them with H
. Let's take your example further, consider this:
package main
import "fmt"
func compare(a, b int) {
if a + b < a * b {
fmt.Printf("hello, world\n")
}
}
After the same gofmt
command the above code becomes:
package H
import "fmt"
func H(H, H H) {
if H+H < H*H {
H
}
}
If this is not what you want, then you should use a more specific pattern expression.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论