我的gofmt工作有问题还是我理解错了什么?

huangapple go评论66阅读模式
英文:

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 &quot;fmt&quot;

func compare(a, b int) {
	if a + b &lt; a * b {
		fmt.Printf(&quot;hello, world\n&quot;)
	}
}

After the same gofmt command the above code becomes:

package H

import &quot;fmt&quot;

func H(H, H H) {
	if H+H &lt; H*H {
		H
	}
}

If this is not what you want, then you should use a more specific pattern expression.

huangapple
  • 本文由 发表于 2017年2月5日 14:40:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/42049267.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定