whitespace は関数やブロックの先頭・末尾にある不要な空行を検出するツールです。
解決する問題
関数や if、for などのブロックの先頭・末尾に不要な空行があると、コードの一貫性が損なわれます。チーム内でスタイルがばらつき、差分レビュー時のノイズにもなります。
1 2 3 4 5 6 7 8 9 10 11 12
| func ProcessOrder(ctx context.Context, order Order) error {
if order.ID == "" {
return errors.New("order ID required")
}
return save(ctx, order)
}
|
1 2 3 4 5 6 7 8
| func ProcessOrder(ctx context.Context, order Order) error { if order.ID == "" { return errors.New("order ID required") }
return save(ctx, order) }
|
設定
公式ドキュメント
1 2 3 4 5 6 7 8 9 10
| version: "2"
linters: enable: - whitespace settings: whitespace: multi-if: false multi-func: false
|
オプション
| オプション |
型 |
デフォルト |
説明 |
multi-if |
bool |
false |
複数行の if 文の後に空行を要求する |
multi-func |
bool |
false |
複数行の関数シグネチャの後に空行を要求する |
サンプル
検出例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
|
func example1() { doSomething() }
func example2() { doSomething() }
func example3(ok bool) { if ok { doSomething() } }
func example4(items []string) { for _, item := range items { process(item) } }
|
修正例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| func example1() { doSomething() }
func example2() { doSomething() }
func example3(ok bool) { if ok { doSomething() } }
func example4(items []string) { for _, item := range items { process(item) } }
|
multi-func / multi-if オプション
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| func LongFunction( ctx context.Context, userID string, options Options, ) error { return process(ctx, userID, options) }
if condition1 && condition2 && condition3 { doSomething() }
|
注意点
- デフォルトではブロックの先頭・末尾の不要な空行のみを検出する。
multi-if と multi-func はオプトイン
- ブロック内の中間にある空行(ロジックの区切り)は検出対象外
gofmt はこの種の空行を修正しないため、whitespace で補完する
参考リンク