4 ms·
Not only does gofmt make the code consistent for people, it makes it machine consistent. Once the code is "fmted" parsing, replacing, etc is simple. Which, bt
by jweir 14y ago
Not only does gofmt make the code consistent for people, it makes it machine consistent. Once the code is "fmted" parsing, replacing, etc is simple.
Which, btw, gofmt does does pattern replacement.
http://golang.org/cmd/gofmt/ http://golang.org/cmd/gofmt/
- NateDad 14y agoThere's a parser in the standard library that makes parsing Go code simple (regardless of format). This is actually what gofmt uses, I believe.
- 4ad 14y agoYou are correct. I'll also add that consistent formatting provides an excellent aid for grepping. Sometimes you want to search for code in the standard library that does something similar to what you do, or you are looking for a specific idiom. Consistent formatting helps making a simple regular expression pretty exhaustive. Combined with structural regular expressions you can answer questions like "what are the types that contain both a mutex and a map, and what are the types that contain the types that use a map without a mutex": http://pastebin.ca/2202690 http://pastebin.ca/2202690
- shurcooL 14y agoThe pattern replacing is awesome. It can do a lot of refactoring. http://talks.godoc.org/github.com/sunfmin/talks/2013/gofmt.slide#1 http://talks.godoc.org/github.com/sunfmin/talks/2013/gofmt.s...
- pjmlp 14y agoIf this is refactoring, then you never used a proper IDE with refactoring support. Slide 5 is the proof this is no better than search and replace.
- NateDad 14y agoHonestly, that's not a very good representation of what gofmt can do. This is a much better example: http://research.swtch.com/gofmt http://research.swtch.com/gofmt gofmt -w -r 'x[i:len(x)] -> x[i:]' *.go Note that this is not a regular expression... it's looking for go expressions that match that pattern. So, for example, this will catch this: a := charts[start:len(charts)] and convert it to this: a := charts[start:]
- chimeracoder 14y agoAlso, a regex will replace matching strings in incorrect places (like a string literal that happens to contain Go code). You can design your regex around this, but at some point, you'll end up just reinventing a Go parser inside a hideous, unmaintainable regex. So you might as well just use gofmt.
- danieldk 14y agoTrue, it's much more than simple search and replace, since it produces an AST, which provides more powerful refactoring. It's also not very spectacular, since it's what Java IDEs have done for ages, plus incremental compiling :). (Or code analysis tools such as Sonatype.) Go is just playing catch-up here. The one thing they did very well is dictating the code style with gofmt. You may not like it, but at least there is once standard. Though, one wonders how many developers and businesses use whatever layout Eclipse or Netbeans use out of the box ;).