1

gofmt command supports -r flag to use rewrite rule during formatting the code. How to use it to replace tabs indentation with the spaces indentation?

Psylone
  • 2,788
  • 1
  • 18
  • 15

2 Answers2

5

Go's format forced by gofmt dictates to use tab indentation. Also see the decision lead to it: https://code.google.com/p/go/issues/detail?id=7101

blang
  • 2,090
  • 2
  • 18
  • 17
3

Command gofmt

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.

The tab and space characters are not valid Go expressions. It won't work.

The Go Programming Language

Alan A. A. Donovan & Brian W. Kernighan

ISBN: 978-0134190440

gopl.io

Go takes a strong stance on code formatting. The gofmt tool rewrites code into the standard format, and the go tool’s fmt subcommand applies gofmt to all the files in the specified package, or the ones in the current directory by default. All Go source files in the book have been run through gofmt, and you should get into the habit of doing the same for your own code. Declaring a standard format by fiat eliminates a lot of pointless debate about trivia and, more importantly, enables a variety of automated source code transformations that would be infeasible if arbitrary formatting were allowed.

Always use gofmt code formatting.

peterSO
  • 158,998
  • 31
  • 281
  • 276
  • Coders can, and do, choose different tab widths in their editor. So, by picking tabs as the standard, Go in fact enforced inconsistent programmer experience :( Also, the last quoted rationale means that , no matter what formal syntax rules are, Go has in fact meaningful indentation just like Python. It's fine to make a decision and stick with it, but we should be honest about the effects. – q.undertow Jul 22 '23 at 18:49