golang for loop は break でも retrun でも抜けられる

f:id:pigggg:20210915204935p:plain

タイトルの通り

forはいつもbreakで抜けていた…
 

return で抜ける

package main

import (
    "fmt"
)

func main() {
    for {
        fmt.Println("Hello, playground")
        return
    }
}

// 結果
Hello, playground

 

breakで抜ける

package main

import (
    "fmt"
    "strconv"
)

func main() {
    index := int64(0)
    for {
        if index > 10 {
            break
        }
        fmt.Println(strconv.FormatInt(index, 10) + ": Hello, playground")
        index++
    }
}

// 結果
0: Hello, playground
1: Hello, playground
2: Hello, playground
3: Hello, playground
4: Hello, playground
5: Hello, playground
6: Hello, playground
7: Hello, playground
8: Hello, playground
9: Hello, playground
10: Hello, playground