Last Updated: February 25, 2016
·
519
· chewxy

Export variables with ease with gofmt

So you wrote a bunch of code, and now you realize that a lot of internal methods/variables/fields you thought only needed to stay internal, now actually need to be exported.

You look to your Find-and-Replace macros, and you despair, because the variable you want to export is "x", but you have variables like "xSomethingElse".

Not to worry, gofmt comes for your rescue.

Let's assume your code looks like that:

package main
import "fmt"

type useless struct {
    var1 int
    var2 int
}

func main() {
    x := useless{1,2}
    fmt.Println(x.var1 * x.var2)
}

You can run this command gofmt -r 'var1 -> Var1' to reformat your code. It will now look like this:

package main
import "fmt"

type useless struct {
    Var1 int
    var2 int
}

func main() {
    x := useless{1,2}
    fmt.Println(x.Var1 * x.var2)
}

Gofmt rewards programmers who are conscientious about their naming conventions. This will not work if you do this: gofmt -r 'var1 -> x'. It will screw with the formatter and your code might end up something like this:

package x
import "fmt"

type x x

func x() {
        x := x
        x
}

That means if you have stuff like structs that have fields of the same name, you're still gonna have to manually find and replace using Ctrl+H.