gofmt: Formatting the go code

10 / Jul / 2014 by Sahil Chitkara 0 comments

golang

When i started working on golang, some interesting things came out related to formatting.

Till now we used to use IDE formatting and indentation with combos like "ctrl+shift+f" or something else, so!! what if your machine could take care of all the formatting issues? and what if it not only works at file level but also at package level. Need i convince you any more? 😉

Let see how it happens:

gofmt

gofmt read the go program and show the result after indentation, vertical alignment and even re formats comments too.

commands and options
gofmt filename : This will print reformatted code.
gofmt -w filename : This will reformat the code and updates the file.
gofmt -r 'rule' filename : Apply the rewrite rule to the source before reformatting.
gofmt /path/to/package : This will format the whole package.

Here is small example for gofmt
filename: demo.go

[js]
package main
import "fmt"
// this is demo to format code
// with gofmt command
var a int=2;
var b int=5;
var c string= `hello world`;
func print(){
fmt.Println("Value for a,b and c is : ");
fmt.Println(a);
fmt.Println((b));
fmt.Println(c);
}
[/js]

Command: gofmt demo.go
Output:

[js]
package main

import "fmt"

// this is demo to format code
// with gofmt command
var a int = 2
var b int = 5
var c string = `hello world`

func print() {
fmt.Println("Value for a,b and c is : ")
fmt.Println(a)
fmt.Println((b))
fmt.Println(c)
}
[/js]

In above example we can see that there are multiple parenthesis around variable b,so below command will remove the extra parenthesis from println statement and will update the file too. Rule must be provide with -r option.
command: gofmt -r '(a) -> a' -w demo.go
output:

[js]
package main

import "fmt"

// this is demo to format code
// with gofmt command
var a int = 2
var b int = 5
var c string = `hello world`

func print() {
fmt.Println("Value for a,b and c is : ")
fmt.Println(a)
fmt.Println(b)
fmt.Println(c)
}
[/js]

I hope you are liking this interesting feature of golang. Stay tuned for more interesting features of golang in upcoming blogs.

FOUND THIS USEFUL? SHARE IT

Leave a Reply

Your email address will not be published. Required fields are marked *