LoginSignup
0
1

More than 3 years have passed since last update.

Goでforとselectを抜ける方法

Posted at

既に似たような記事もありますが、備忘録ように記載しておきます。

for selectでbreakとしても抜け出せないので、下記のようにgotoを使用すると抜け出せます。

main.go

package main

import (
    "fmt"
    "time"
)

func main() {

    i := 0
    ticker := time.NewTicker(1 * time.Second)
    defer ticker.Stop()

    for {
        select {
        case <-ticker.C:
            fmt.Printf("COUNT : %d\n", i)
            if i == 5 {
                goto GOTO_FINISH
            }
            i++
        }
    }

GOTO_FINISH:
    fmt.Println("GOTO_FINISH")
}
0
1
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
0
1