[Go Tour 2] process control statement

Posted by Fitzlegend on Mon, 20 Sep 2021 18:21:37 +0200

1, for

Go has only one loop structure: for   Cycle.

Basic   for   The loop consists of three parts separated by semicolons:

  • Initialization statement: executed before the first iteration
  • Conditional expressions: evaluate before each iteration
  • Post statement: executed at the end of each iteration

The initialization statement is usually a short variable declaration, which is only used in   for   Is visible in the scope of the statement.

Once the Boolean value of the conditional expression is   false, the loop iteration will terminate.

Note: unlike languages such as C, Java and JavaScript, there are no parentheses and braces outside the three components behind the Go for statement   { }   Is necessary.

package main

import "fmt"

func main() {
	sum := 0
	for i := 0; i < 10; i++ {
		sum += i
	}
	fmt.Println(sum)
}

Initialization and post statements are optional.

package main

import "fmt"

func main() {
	sum := 1
	for ; sum < 1000; {
		sum += sum
	}
	fmt.Println(sum)
}

for is "while" in Go

At this point, you can remove the semicolon because of C   while   In Go, it's called   for.

package main

import "fmt"

func main() {
	sum := 1
	for sum < 1000 {
		sum += sum
	}
	fmt.Println(sum)
}

2, if

Go   if   Statement and   for   Like a loop, no parentheses are required outside the expression   ( )  , And braces   { }   Is necessary.

package main

import (
	"fmt"
	"math"
)

func sqrt(x float64) string {
	if x < 0 {
		return sqrt(-x) + "i"
	}
	return fmt.Sprint(math.Sqrt(x))
}

func main() {
	fmt.Println(sqrt(2), sqrt(-4))
}

Short if statement

with   for   Like,   if   Statement can execute a simple statement before a conditional expression.

The variable scope declared by this statement is only in   if   Within.

(at the end)   return   Use at statement   v   Look.)

package main

import (
	"fmt"
	"math"
)

func pow(x, n, lim float64) float64 {
	if v := math.Pow(x, n); v < lim {
		return v
	}
	return lim
}

func main() {
	fmt.Println(
		pow(3, 2, 10),
		pow(3, 3, 20),
	)
}

Exercise: loops and functions

To practice functions and loops, let's implement a square root function: the square root function is implemented by Newton's method.

Computers usually use loops to calculate the square root of x. Starting with a guessed value z, we can use z ² Adjust z with the approximation of x to produce a better guess:

z -= (z*z - x) / (2*z)

Repeat the adjustment process, the guess result will become more and more accurate, and the answer will be as close to the actual square root as possible.

In the provided   func Sqrt   Implement it in. Whatever the input is, a good guess for z is 1. To start, repeat the calculation 10 times and print the z value each time. Observe how the answer you get approximates the result for different values x (1, 2, 3...), and guess how fast the improvement is.

Tip: declare and initialize a floating-point value using type conversion or floating-point syntax:

z := 1.0
z := float64(1)

Then, the loop condition is modified so that the loop exits when the value stops changing (or the change is very small). Observe whether the number of iterations is greater than or less than 10. Try changing the initial guess of z, such as x or x/2. Your function results are the same as those in the standard library   math.Sqrt   Close?

(Note:   If you are interested in the details of the algorithm, click z above ² − x is z ² The distance to the value it wants to reach (i.e. x), divided by 2z is z ² The derivative of z, we pass z ² To change the adjustment of z. this general method is called Newton method (it is very effective for many functions, especially the square root.)

package main

import (
	"fmt"
	"math"
)

func Sqrt(x float64) float64 {
	z := 1.0
	for i:=0;i<=10;i++ {
		z -= (z*z - x) / (2 * z)
		fmt.Println("z=%f,i=%d", z, i)
	}
	return z
}

func main() {
	fmt.Println(Sqrt(2))
	fmt.Println(Sqrt(2))
}

3, switch

switch   Is to write a series of   if - else   Statement. It runs the first case statement whose value is equal to the conditional expression.

Go's switch statements are similar to those in C, C + +, Java, JavaScript and PHP, but go only runs the selected cases, not all subsequent cases. In fact, go automatically provides the information required after each case in these languages   break   sentence. Unless   fallthrough   Statement ends, otherwise the branch terminates automatically. Another important difference of go is that the case of switch does not need to be constant, and the value does not need to be an integer.

package main

import (
	"fmt"
	"runtime"
)

func main() {
	fmt.Print("Go runs on ")
	switch os := runtime.GOOS; os {
	case "darwin":
		fmt.Println("OS X.")
	case "linux":
		fmt.Println("Linux.")
	default:
		// freebsd, openbsd,
		// plan9, windows...
		fmt.Printf("%s.\n", os)
	}
}

Evaluation order of switch

The case statements of switch are executed sequentially from top to bottom until the matching is successful.

(for example,

switch i {
case 0:
case f():
}

stay   i==0   Time   f   Will not be called.)

package main

import (
	"fmt"
	"time"
)

func main() {
	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.")
	}
}

Unconditional switch

Unconditional switch   switch true   Same.

This form can write a long string of if then else more clearly.

package main

import (
	"fmt"
	"time"
)

func main() {
	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.")
	}
}

defer

The defer statement delays the execution of the function until the outer function returns.

The parameters of a deferred function are evaluated immediately, but the function will not be called until the outer function returns.

package main

import "fmt"

func main() {
	defer fmt.Println("world")

	fmt.Println("hello")
}

defer stack

Deferred function calls are pushed onto a stack. When the outer function returns, the deferred function will be called in last in first out order.

package main

import "fmt"

func main() {
	fmt.Println("counting")

	for i := 0; i < 10; i++ {
		defer fmt.Println(i)
	}

	fmt.Println("done")
}

Topics: Go