Quick Go Hack - Renaming Structs

Sep 26 2015

Today I found myself needing to rename a struct throughout the codebase of a project. In many languages, doing this would either require some perl/sed kung-fu or an IDE tool like you'd find in IntelliJ. Go, however, comes with a handly tool for doing this: gofmt. That's right, it does more than just fix your whitespace.

Here's the command I issued to re-name my struct:

gofmt -r 'GlobalAttributes -> HTML' -w ./

In a nutshell, this looks for the name GlobalAttributes and replaces it with the name HTML (the -> arrow operator indicates the replacement). It is "lexically aware", so it knows what instances to change and what not to. (You could, for example, use it to change the names of a field on a struct without doing a global find-and-replace).

The -r flag is used to declare a replacement, and the -w flag indicates that the results should be written to their respective files.

Preview, Please!

If you'd rather just see a preview of what is to be changed, you can remove the -w flag, which will write the entire thing to standard out. Or, better yet, add the -d flag, which will generate a diff:

gofmt -r 'GlobalAttributes -> HTML' -d ./
diff form/button.go gofmt/form/button.go
--- /var/folders/hb/h4369mv96dn0h1yz7fc41j_r0000gn/T/gofmt237734033 2015-09-26 10:11:05.000000000 -0600
+++ /var/folders/hb/h4369mv96dn0h1yz7fc41j_r0000gn/T/gofmt738333884 2015-09-26 10:11:05.000000000 -0600
@@ -1,7 +1,7 @@
 package form

 type Button struct {
-   GlobalAttributes
+   HTML
    Autofocus, Disabled           bool
    Form, Menu, Name, Type, Value string
 }
diff form/fieldset.go gofmt/form/fieldset.go
--- /var/folders/hb/h4369mv96dn0h1yz7fc41j_r0000gn/T/gofmt769223915 2015-09-26 10:11:05.000000000 -0600
+++ /var/folders/hb/h4369mv96dn0h1yz7fc41j_r0000gn/T/gofmt570539854 2015-09-26 10:11:05.000000000 -0600
@@ -1,7 +1,7 @@
 package form

 type FieldSet struct {
-   GlobalAttributes
+   HTML
  Form, Name string

And that's a simple way to refactor a Go project without requiring any special tools.

The mapping tool for gofmt is even more sophisticated than the above example would indicate. Learn more at the Go website.


This is the first in a series called "Quick Go Hacks" that covers simple solutions to common Go questions.