2

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
}
janos
  • 120,954
  • 29
  • 226
  • 236
Andy D
  • 125
  • 13

1 Answers1

5

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.

janos
  • 120,954
  • 29
  • 226
  • 236