Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using the gofmt refactoring tool to rename a global variable

Tags:

go

refactoring

I'm experimenting the gofmt tool capabilities for refactoring go code based on this blog post, I have this trivial example:

package main

import (
    "fmt"
)

var v = 12

func main() {
    fmt.Println(v)
}

I'm trying to rename the v variable to mapplying this recipe:

gofmt -r 'v -> m' -w main.go

The code after the refactoring looks (broken) like:

package m

import (
    "fmt"
)

var m = m

func m() {
    m
}

What am I missing here?

like image 873
Salah Eddine Taouririt Avatar asked Feb 11 '14 14:02

Salah Eddine Taouririt


1 Answers

There is a problem with what you're trying, the gofmt manual states:

The rewrite rule specified with the -r flag must be a string of the form:

pattern -> replacement

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.

(highlighting added)

If you had var vee = 12 and used -r vee -> foo everything would be fine. With v -> m however, v -> m matches every Go expression, identifies it as v and replaces it by m.

like image 132
nemo Avatar answered Oct 15 '22 12:10

nemo