For Loop

Go์˜ Loop๋ฅผ ์•Œ์•„๋ณด์•„์š”

For

  • Go์˜ looping์€ ์˜ค์ง for loop ํ•˜๋‚˜๋งŒ ๊ฐ€๋Šฅํ•˜๋‹ค

Range

  • slice๋‚˜ map์— loop๋ฅผ ์ ์šฉํ•  ์ˆ˜ ์žˆ๋„๋ก ํ•ด์ค€๋‹ค

    • range๋Š” loop์˜ index์™€ value๋ฅผ ์ค€๋‹ค!

    • ๋‹จ, for ์•ˆ์—์„œ๋งŒ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค

    • ex)

      package main
      
      import "fmt"
      
      func addAll(numbers ...int) int {
       total := 0
       // for loop w/ range
       for _, number := range numbers {
        total += number
       }
       return total
      }
      
      func main() {
       total := addAll(1, 2, 3, 4, 5, 6, 7, 8, 9)
       fmt.Println(total)
      }
      
  • range๋ฅผ ํ™œ์šฉํ•˜์—ฌ loop๋ฅผ ์ˆœํšŒํ•˜๋ฉด, ์•„๋ž˜์™€ ๊ฐ™์ด ๋‘ ๊ฐœ์˜ value๋ฅผ return ํ•œ๋‹ค

    1. index

    2. copy of the element at that index

  • ๋งŒ์•ฝ index๊ฐ€ ํ•„์š” ์—†๊ณ  ๊ฐ’๋งŒ ํ•„์š”ํ•˜๋‹ค๋ฉด, ์œ„์˜ ์˜ˆ์‹œ์ฒ˜๋Ÿผ ignored value์ธ underscore (_) ๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ๋œ๋‹ค

+

range ๋ฅผ ์‚ฌ์šฉํ•œ for loop๋Š” python ์˜ enumerate ์™€ ์œ ์‚ฌํ•˜๋‹ค!

Range๋ฅผ ์‚ฌ์šฉํ•˜์ง€ ์•Š์€ for

  • Range ์—†์ด๋„ for loop๋ฅผ ๋งŒ๋“ค ์ˆ˜ ์žˆ๋‹ค

    • ex)

      func add(numbers ...int) {
       for i := 0; i < len(numbers); i++ {
        fmt.Println(i)
       }
      }
  • but, ์ฝ”๋“œ๊ฐ€ ๊ธธ์–ด์ง€๊ณ  ๋น„ํšจ์œจ์ ์ด๋ฏ€๋กœ ์•ˆ ์“ฐ๊ฒŒ ๋  ๊ฒƒ ๊ฐ™๋‹ค!

Last updated