I'm going to write the understanding of Go from the basics of programming!
for i := 1; i <= 4; i ++ { //Variable initialization;Repeating conditions;Variable update
fmt.Println("Hello")
}
//console
Hello
Hello
Hello
Hello
1 is assigned to the variable i, and the processing in {} is repeated while "i is 4 or less" is satisfied. Variable update "i ++" is executed every time it finishes
//Flow of iterative processing
❶ Initialization of variables
❷ Conditions
❸ Repeated processing
❹ Variable update
❷...
for i := 1; i <= 5; i ++ { //❶i:=1;❷i<=5;❹i++
fmt.Println(i) //❸fmt.Println(i)
}
//console
1
2
3
4
5
Variable i is 1 in the first lap of repetition Every time the processing (③) in {} of for is completed, the variable i is updated (④) and changes to 1,2,3,4,5. And when i <= 5 (②) does not hold, the repetition ends automatically.
func main() {
for i := 1; i <=3; i ++ {
fmt.Println("Hello")
fmt.Println(i)
}
}
//console
Hello
1
Hello
2
Hello
3
If you write multiple processes in the {} of for, it will be repeated in the order in which they were written.
for var i int =1; i <= 4; i ++ { //Variable definition using var
fmt.Println("Hello")
}
//console
Error that variable definition by var cannot be done with for statement
You cannot use var in the variable definition of the for statement You can only define variables using: =
package main
import "fmt"
func main() {
for i := 1; i <= 100; i ++ {
fmt.Println(i)
}
}