Search code examples
gogofmt

Does my gofmt work wrongly or I don't understand something?


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
}

Solution

  • 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.