1. For loop
Go has only one looping construct - for
loops
The for loop consists of three components separated by semicolons:
Initialization Statement: Executed before the first loop execution Optional
Loop conditional expression: Evaluated before each iteration: false or true Required
post-statement: executed after each iteration optional
Example 1 Common loop:
package main import "fmt" func main() { sum := 0 for i := 0; i < 10; i++ { sum += i } fmt.Println(sum) }Example 2 retains only the loop conditional expression:
package main import "fmt" func main() { sum := 1 for ; sum < 1000; { sum += sum } fmt.Println(sum) }Example three infinite loop:
package main func main() { for { } }
DEMO :
package main import "fmt" func main() { var i, j int //calculate prime numbers within 100 for i = 2; i < 100; i++ { for j = 2; j <= i/j; j++ { if i%j == 0 { break // if factor found, not prime } } if j > (i / j) { fmt.Printf("%d is prime\n", i) } } // string reverse str := "hello world" arr := []rune(str) for i,j := 0,len(arr)-1;i<len(arr)/2;i,j = i+1,j-1{ arr[i],arr[j] = arr[j],arr[i] } fmt.Println(string(arr)) }
Two, if
conditional expression
A simple statement can be executed before the condition, the scope of the variable defined by this statement is only within the scope of the if
Example:
package main import ( "fmt" "math" ) func main() { /* define local variables */ var a int = 10 /* Use if statement to evaluate boolean expressions */ if a < 20 { /* If the condition is true, execute the following statement */ fmt.Printf("a is less than 20\n") } fmt.Printf("The value of a is: %d\n", a) fmt.Println(pow(2, 3, 10)) fmt.Println(pow(3, 3, 20)) } func pow(x, n, lim float64) float64 { //if statement can execute a simple statement before the condition if v := math.Pow(x, n); v < lim { return v } else { //Variables defined in the if convenience statement can also be used in any corresponding else block fmt.Printf("%g >= %g\n", v, lim) } //This place cannot use the variable v defined in if return lim }
DEMO: Calculate the square root using Newton's method
Simplified z = z/2 + x/2*z
/** Exercise: Loops and Functions As an easy way to practice functions and loops, use Newton's method to implement square root functions */ package main import ( "fmt" ) func Sqrt(x float64) float64 { z: = float64 (1) for i := 0; i < 1e+5; i++ { z = z/2 + x/(2*z) } return z } func main() { fmt.Println(Sqrt(4)) }
Three, switch
The condition of switch is executed from top to bottom, and stops when a match is successful
A switch without a condition is the same switch true
as if-then-else
Example 1:
package main import ( "fmt" "runtime" ) func main() { /* define local variables */ var grade string = "B" var marks int = 90 switch marks { case 90: grade = "A" case 80: grade = "B" case 50, 60, 70: grade = "C" default: grade = "D" } switch { case grade == "A": fmt.Printf("Excellent!\n") case grade == "B", grade == "C": fmt.Printf("Good\n") case grade == "D": fmt.Printf("Pass\n") case grade == "F": fmt.Printf("Failed\n") default: fmt.Printf("差\n") } fmt.Printf("Your grade is %s\n", grade) fmt.Println(runtime.GOOS) switch os := runtime.GOOS; you { case "windows": fmt.Println("system is " + os) case "linux": fmt.Println("Linux.") default: fmt.Printf("%s.", os) } }
Example two:
package main
import (
"fmt"
"time"
)
func main() {
var x interface{}
//switch executes from top to bottom and stops when the match is successful
switch i := x.(type) {
case nil:
fmt.Printf("Type of x: %T", i)
case int:
fmt.Printf("x is of type int")
case float64:
fmt.Printf("x is float64")
case func(int) float64:
fmt.Printf("x is of type func(int)")
case bool, string:
fmt.Printf("x is bool or string")
default:
fmt.Printf("Unknown type")
}
fmt.Println("When's Saturday?")
today := time.Now().Weekday()
switch time.Saturday {
case today + 0:
fmt.Println("Today.")
case today + 1:
fmt.Println("Tomorrow.")
case today + 2:
fmt.Println("In two days.")
default:
fmt.Println("Too far away.")
}
// switch without condition is equivalent to if-then-else chain
t := time.Now()
switch {
case t.Hour() < 12:
fmt.Println("Good morning!")
case t.Hour() < 17:
fmt.Println("Good afternoon.")
default:
fmt.Println("Good evening.")
}
}
Four, defer delay
The defer statement delays the execution of a function until the upper function returns
The parameters of the delayed call will be generated immediately, but the function will not be called until the upper function returns
Delayed function calls are pushed onto a stack. When the function returns, the delayed function calls are called in LIFO order
Example:
package main import "fmt" func main() { //The defer statement will delay the execution of the function until the upper function returns. defer fmt.Println("world") fmt.Println("hello") i := 1 //The parameters of the delayed call will be generated immediately, but the function will not be called until the upper function returns //Delayed function calls are pushed onto a stack. When the function returns, the delayed function calls are called in LIFO order defer fmt.Println(i) i++ fmt.Println(i) }