Golang Tabs vs Space for indentation - Formatting Tips


Tuan Nguyen

GO

Recommended Golang Formatting Tips

From the Effective go  document:

Formatting issues are the most contentious but the least consequential. People can adapt to different formatting styles but it's better if they don't have to, and less time is devoted to the topic if everyone adheres to the same style. The problem is how to approach this Utopia without a long prescriptive style guide.

With Go we take an unusual approach and let the machine take care of most formatting issues. The gofmt program (also available as go fmt, which operates at the package level rather than source file level) reads a Go program and emits the source in a standard style of indentation and vertical alignment, retaining and if necessary reformatting comments. If you want to know how to handle some new layout situation, run gofmt; if the answer doesn't seem right, rearrange your program (or file a bug about gofmt), don't work around it.

As an example, there's no need to spend time lining up the comments on the fields of a structure. Gofmt will do that for you. Given the declaration:

type T struct {
    name string // name of the object
    value int // its value
}

gofmt will line up the columns:

type T struct {
    name    string // name of the object
    value   int    // its value
}

We use tabs for indentation and gofmt emits them by default. Use spaces only if you must. Tabs for indentation is the official recommendation.

 

Golang Tabs Vs Spaces—what is the proper indentation character

Using Spaces

A tab could be a different number of columns depending on your environment, but a space is always one column.

In terms of how many spaces (or tabs) constitutes indentation, it's more important to be consistent throughout your code than to use any specific tab stop value.

 

Using Tabs

Now, of course, consistency matters more than either one, and a good IDE makes the differences negligible. That said, the point of this thread is to be a holy war, so:

  • They're a character specifically meant for indentation
  • They allow developers with different preferences in indentation size to change how it's the code looks without changing the code (separation of data and presentation for the proverbial win!)
  • It's impossible to half-indent something with tabs. So when you copy code from some website that used 3 spaces into your 4-space indented file, you don't have to deal with misalignment.

Again, in Golang, Use spaces only if you must. Tabs for indentation is the official recommendation.

 

Fix indentation automatically

Method-1: Using go fmt

The Go development tools include a command, go fmt, which automatically reformats your code to match the standard format. It does things like fixing up the whitespace for indentation, lining up the fields in a struct, and making sure there is proper spacing around operators.

package main

import "fmt"

func main() {
                myvar := "deepak"


                if myvar == "deepak" {
                                fmt.Println("Found")
                } else {
fmt.Println("Not Found") 
                }


        }

Next let's execute go fmt command:

$ go fmt main.go

Next re-verify the script's indentation and you will see that it is perfectly formatted:

package main

import "fmt"

func main() {
        myvar := "deepak"

        if myvar == "deepak" {
                fmt.Println("Found")
        } else {
                fmt.Println("Not Found")
        }

}

 

Method-2: Using goimports

There’s an enhanced version of go fmt available called goimports that also cleans up your import statements. It puts them in alphabetical order, removes unused imports, and attempts to guess any unspecified imports. Its guesses are sometimes inaccurate, so you should insert imports yourself.

To download goimports you can execute:

$ go install golang.org/x/tools/cmd/goimports@latest

Once installed you can directly execute goimports or check for this binary in your GOPATH path:

$ go env GOPATH
/root/go

Here I have a sample main.go file which contains some unused elements such as "import log" and "unusedvar".

package main

		import "fmt"
	import "log"

			func main() {
		myvar := "deepak"
  unusedvar := "rohit"
if myvar == "deepak" {
fmt.Println("Found")
} else {
fmt.Println("Not Found")
}

}

So let's use goimport to fix this code in terms of removal of unwanted code and indentation. The -l flag tells goimports to print the files with incorrect formatting to the console. The -w flag tells goimports to modify the files in-place. The . specifies the files to be scanned: everything in the current directory and all of its subdirectories.

$ /root/go/bin/goimports -l -w .
main.go

Now verify the code again, as you can see all unused code is automatically removed and the indentation has been fixed.

package main

import "fmt"

func main() {
	myvar := "deepak"
	unusedvar := "rohit"
	if myvar == "deepak" {
		fmt.Println("Found")
	} else {
		fmt.Println("Not Found")
	}

}

 

How to avoid indentation issues in GO?

Which we can work small Go programs using any file editor but in the long run you will need more advanced tools while working on larger project. You can find a bunch of such tools for most text editors and IDE.

Our personal preference is Visual Studio Code from Microsoft. Since it was released in 2015, VS Code has become the most popular source code editor for developers. It does not ship with Go support, but you can make it a Go development environment by downloading the Go extension from the extensions gallery.

We have written a detailed article on getting started with go programming language using Visual Studio Code.

 

Summary

As a professional programmer, what do you prefer, tabs or spaces? As a professional programmer, I use a formatter that formats my code to whatever the accepted standards of the language

with default parameters (gofmt in Go). So it will make the core and are, at least, reasonably well understood.

 

References

https://go.dev/doc/effective_go#formatting

 

Views: 92

Tuan Nguyen

He is proficient in Golang, Python, Java, MongoDB, Selenium, Spring Boot, Kubernetes, Scrapy, API development, Docker, Data Scraping, PrimeFaces, Linux, Data Structures, and Data Mining. With expertise spanning these technologies, he develops robust solutions and implements efficient data processing and management strategies across various projects and platforms. You can connect with him on LinkedIn.

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can send mail to admin@golinuxcloud.com

Thank You for your support!!

Leave a Comment

GoLinuxCloud Logo


We try to offer easy-to-follow guides and tips on various topics such as Linux, Cloud Computing, Programming Languages, Ethical Hacking and much more.

Programming Languages

JavaScript

Python

Golang

Node.js

Java

Laravel