This paper mainly introduces the loop grammar in Go language, which is convenient for beginners to quickly get started with Go grammar. If there is any wrong or unreasonable description in the article, please leave a message. I will check and correct it in time every day.

There are several common ways to write a loop

  • The standard of writing
func test0001(a) {
	sum := 0
	// For does not need parentheses
	// we can omit the initial condition, the end condition, and the increment expression in the for condition
	for i := 1; i <= 100; i++ {
		sum += i;
	}
	fmt.Println(sum)
}
Copy the code
  • Omit the initial condition - equivalent to the while loop in other languages
// convertTOBin Converts decimal to binary
func convertToBin(num int) string {
	result := ""
	// The initial condition is omitted from the for loop, equivalent to while
	// /= operator: divide and then assign
	for ; num > 0; num /= 2 {
		lsb := num % 2
		result = strconv.Itoa(lsb) + result
	}
	return result
} 
Copy the code
  • The for loop omits the initial condition, the increment condition, and the end condition, which is equivalent to an infinite loop
When running this code: remember to create a new a.txt file first
func printFile(filename string) {
	file, err := os.Open(filename)
	iferr ! =nil {
		panic(err)
	}
	scanner := bufio.NewScanner(file)
	// Omit the initial condition, increment condition, equivalent to the while loop
	for scanner.Scan() {
		fmt.Println(scanner.Text())
	}
}
printFile(a.txt)
Copy the code
  • Infinite loop
func endlessLoop(a) {
	// 
	for {
		fmt.Println("hello go")}}Copy the code