0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[Golang]Goでの繰り返し処理をまとめる

Posted at

はじめに

改めてGoの繰り返し処理についてまとめて行きます。

for文

普通のfor文

  for i := 1; i <= 5; i++ {
        fmt.Println(i)
        // 1,2,3,4,5
    }

continueを使って、スキップする

for i := 0; i < 10; i++ {
    if i%2 == 0 {
        continue
    }
    fmt.Println(i)
}

breakを使って処理を終了する

for i := 0; i < 10; i++ {
    if i == 5 {
        break
    }
    fmt.Println(i)
}

for range

for i, v := range []string{"foo", "bar", "baz"} {
    fmt.Println(i, v)
}

結果
0 foo
1 bar
2 baz

連想配列を使う場合

for k, v := range map[string]int{"key-1": 100, "key-2": 200, "key-3": 300} {
    fmt.Println(k, v)
}

結果
key-1 100
key-2 200
key-3 300

Eachを使いたい人向け

package main
import "fmt"


type StrSlice []string

func (a StrSlice) Each(f func(i int, v string)) {
    for i, v := range a {
        f(i, v)
    }
}

type IntSlice []int

func (a IntSlice) Each(f func(i int, v int)) {
    for i, v := range a {
        f(i, v)
    }
}

func main() {
    StrSlice{"foo", "bar", "baz"}.Each(func(i int, v string) {
        fmt.Println(i, v)
    })

    IntSlice{10, 20, 30}.Each(func(i int, v int) {
        fmt.Println(i, v)
    })
}

終わりに

多言語にあるようなeachを使えないことに不満をいだいている人が多いけど、
自分的には、for range使えればいいかなと思ってます。
マジで使いたかったら、上記の用に作っちゃえばいいかなって感じですね!

参考文献

0
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?