LoginSignup
34
27

More than 5 years have passed since last update.

【Go】 go fmt でコード整形

Last updated at Posted at 2015-08-25

goには標準でコードを整形してくれる機能があるようです。そこで、実際にどうフォーマットされるのか試してみました。

go fmt 実行前後のコード比較

元のコード

test.go
package main
import(
"strings"
"fmt"
)
type T struct{
name string // オブジェクトの名前
value int // その値
}
func main(){
sum := 0
for i:=1;i<=10;i++{
if (i > 5) {
s := "iが6以上です"
fmt.Printf("%d\n", s)
fmt.Printf("%v\n", strings.Fields(s))
}
sum += i
}
fmt.Printf("%d\n", sum)
}

読み辛い…けど、一応動きます。(コードに意味はありません。笑)

go fmt の実行

go fmt test.go

フォーマット後のコード

test.go(フォーマット後)
package main

import (
    "fmt"
    "strings"
)

type T struct {
    name  string // オブジェクトの名前
    value int    // その値
}

func main() {
    sum := 0
    for i := 1; i <= 10; i++ {
        if i > 5 { 
            s := "iが6以上です" 
            fmt.Printf("%d\n", s)
            fmt.Printf("%v\n", strings.Fields(s))
        }   
        sum += i
    }   
    fmt.Printf("%d\n", sum)
}

何が変わった?

行間

packageステートメント、importステートメントなどの間に1行空行が挿入されています。

インデント

インデントが挿入されています。また、インデントはデフォルトでハードタブを用います。
https://golang.org/doc/effective_go.html#formatting

Indentation
We use tabs for indentation and gofmt emits them by default. Use spaces only if you must.

import順

パッケージのインポート順が「"strings", "fmt"」から「"fmt", "strings"」に変わっています。
※何順か調べられていないので、ご存知の方ご教授ください><

【追記(2015/09/05)】
以下記事で詳細に触れました。
【Go】go fmt でフォーマット化された後のimportの順番について

構造体のフィールド、コメントのカラムの整列

name, valueの型の縦位置、コメントの縦位置が揃っています。
https://golang.org/doc/effective_go.html#formatting

ifの構文の()

元のコードではifの条件を記述する構文に()が付いていますが、フォーマット後は()が取れています。
https://golang.org/doc/effective_go.html#formatting

Parentheses
Go needs fewer parentheses than C and Java: control structures (if, for, switch) do not have parentheses in their syntax. Also, the operator precedence hierarchy is shorter and clearer, so

開始括弧の前のスペース

fmt 前 fmt 後
import( import (
func main(){ func main() {

のように、フォーマット後は各ブロックの開始括弧の前に半角スペースがつきました。

参考

https://golang.org/doc/effective_go.html#formatting
http://www.slideshare.net/nakaji-s/gophergolanggo-fmt
http://okisanjp.com/archives/4900

34
27
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
34
27