[Go/Golang] Go 언어 반복문

2022. 6. 8. 20:0003. Resources/Go

728x90
반응형

이제 반복문 차례이다

https://gobyexample.com/for

 

Go by Example: For

for is Go’s only looping construct. Here are some basic types of for loops. package main import "fmt" func main() { The most basic type, with a single condition. i := 1 for i <= 3 { fmt.Println(i) i = i + 1 } A classic initial/condition/after for loop. f

gobyexample.com

예제 코드는 아래와 같다.

package main

import "fmt"

func main() {
	i := 1
	for i <= 3 {
		fmt.Println(i)
		i += 1
	}

	for j := 7; j <= 9; j++ {
		fmt.Println(j)
	}

	for {
		fmt.Println("loop")
		break
	}
	for n := 0; n <= 5; n ++ {
		if n%2 == 0 {
			continue
		}
		fmt.Println(n)
	}
}

반복문은 여러가지 종류로 쓸 수 있다.

이터레이터를 미리 선언하고, 반복문 안에서 반복할 수도 있고

	i := 1
	for i <= 3 {
		fmt.Println(i)
		i += 1
	}

c언어 계열처럼 for문 옆에 이터레이터의 조건들을 써 줄 수도 있다.

	for j := 7; j <= 9; j++ {
		fmt.Println(j)
	}

while 1, while true 와 같은 무한 반복은 아무런 이터레이터를 넣지 않으면 가능하고, 강제 종료는 역시 break로 가능하다.

	for {
		fmt.Println("loop")
		break
	}

다른 언어들처럼 중간에 continue로 반복문을 넘어가는 것도 가능하다

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

일단 예제의 앞부분에서 다루는 반복문은 이정도이다!

 

익숙한 표현이라 그리 어렵진 않다.

반응형