Go 기초
Go for Loops
Go has one loop keyword. See its four forms: counting, while-style, infinite and range.
배울 내용
- The three-part for
- for as a while loop
- range
for i := 1; i <= 3; i++
1print
2print
3print
4stop
One keyword, four forms
Go has one loop keyword: for. It can count with three parts, repeat while a condition is true, run forever until break, or visit every item with range.
The first loop has a start, a condition and a step. The second has only a condition, like while in other languages. The third has nothing and ends with break. range over a string gives the position and the character of each letter.
핵심 포인트
- for i := 1; i
<=3; i++ counts. - for condition { } works like while.
- range visits every item.
실행 가능한 Go 예제
Go
main.go
package main
import "fmt"
func main() {
for i := 1; i <= 3; i++ {
fmt.Println("for:", i)
}
countdown := 3
for countdown > 0 { // a while loop
fmt.Println("while:", countdown)
countdown--
}
total := 0
for { // an infinite loop, left with break
total += 10
if total >= 30 {
break
}
}
fmt.Println("loop result:", total)
for index, letter := range "Go" {
fmt.Println(index, string(letter))
}
}
for: 1
for: 2
for: 3
while: 3
while: 2
while: 1
loop result: 30
0 G
1 o연습
예제를 온라인 컴파일러에서 열고 값을 바꾸거나 한 줄을 추가한 다음, 실행하기 전에 출력을 예상해 보세요. 그런 다음 일부러 코드를 망가뜨리고 컴파일러 메시지를 읽어 보세요.
이 레슨을 마쳤나요?
학습 완료로 표시하면 진행 상황을 기록할 수 있습니다.
진행 상황이 이 브라우저에 저장되어 있습니다 로그인하면 모든 기기에서 이어갈 수 있습니다.
챌린지로 연습하기
이 레슨에서 배운 내용으로 실제 문제를 풀어 보세요. 모든 챌린지는 브라우저에서 실행되며 즉시 테스트와 AI 리뷰를 받을 수 있습니다.
- Countdown to Liftoff Count down from a number and end with Liftoff! 쉬움
- Sum of Odd Numbers Add every odd number up to a limit. 쉬움