Created
August 4, 2023 13:43
-
-
Save destinio/3f7ec1cd0cb8c33e6a2eccfbc29229c1 to your computer and use it in GitHub Desktop.
Loops in Go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// standard for loop | |
for i := 0; i < 10; i++ { | |
fmt.Println(i) | |
} | |
// while loop | |
j := 0 | |
for j < 10 { | |
fmt.Println(j) | |
j++ | |
} | |
// Infinite loop | |
i := 0 | |
for { | |
fmt.Println(i) | |
i++ | |
if i > 10 { | |
break | |
} | |
} | |
// loop over a slice | |
numbers := []int{1, 2, 3, 4, 5} | |
for i, n := range numbers { | |
fmt.Println(i, n) | |
} | |
// loop over a map | |
colors := map[string]string{"red": "#ff0000", "green": "#00ff00", "blue": "#0000ff"} | |
for key, value := range colors { | |
println(key, value) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment