LoginSignup
16
15

More than 5 years have passed since last update.

Go でコメントアウトせずに素早く複数行スキップさせる

Last updated at Posted at 2016-04-18

TL; DR

if false {} でスキップしたい箇所を囲む

本文

Go では宣言されてるのに使われてない変数があると、ビルド時に hoge declared and not used といった感じで怒られます。
Go 書いてる時、デバッグ目的で処理を飛ばそうと複数行コメントアウトしたくなる時があります。が、適当にやると変数の宣言だけが残って前述のように怒られることがあります。この場合は改めて宣言箇所だけコメントアウトすればビルドが通りますが、まあ面倒ですよね。

こういう時は、該当箇所を if false {} で囲ってやればよいです。見てわかるように、常に false なのでブロックの中は実行されません。

Example

元のコード

package main

import (
    "fmt"
)

func main() {
    hogeMessage := "hoge"
    fugaMessage := "fuga"
    piyoMessage := "piyo"
    hogehogeMessage := "hogehoge"

    fmt.Println(hogeMessage)
    fmt.Println(fugaMessage)
    fmt.Println(piyoMessage)
    fmt.Println(hogehogeMessage)
}
$ go run hoge.go
hoge
fuga
piyo
hogehoge

コメントアウトすると…

package main

import (
    "fmt"
)

func main() {
    hogeMessage := "hoge"
    fugaMessage := "fuga"
    piyoMessage := "piyo"
    hogehogeMessage := "hogehoge"

    fmt.Println(hogeMessage)
    // fmt.Println(fugaMessage)
    // fmt.Println(piyoMessage)
    fmt.Println(hogehogeMessage)
}
$ go run hoge.go
# command-line-arguments
./hoge.go:9: fugaMessage declared and not used
./hoge.go:10: piyoMessage declared and not used

if false {} で囲むと…!

package main

import (
    "fmt"
)

func main() {
    hogeMessage := "hoge"
    fugaMessage := "fuga"
    piyoMessage := "piyo"
    hogehogeMessage := "hogehoge"

    fmt.Println(hogeMessage)

    if false {
        fmt.Println(fugaMessage)
        fmt.Println(piyoMessage)
    }

    fmt.Println(hogehogeMessage)
}
$ go run hoge.go
hoge
hogehoge

同じようなことを他の言語でやろうとするとブロック内のインデント調整が面倒ですが、Go だと go fmt でよしなにしてくれるので便利ですね。

16
15
0

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
16
15