GO – Flow Control

The All-purpose For loop

GO has a single looping construct which is the For loop. For loop has three components similar to that in C/Javascript:

  • Init statement – Executed before the loop starts
  • Conditional statement – Checked before every iteration
  • Post statement – executed after every iteration.

However, unlike C/Java/Javascript there is no parentheses surrounding the components.

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

The For loop can also be written without the init and the post statements:

for ;i<10; {
   fmt.Println(i)
}

For can also be a while loop:

for i<10 {
   fmt.Println(i)
}

Conditional Statement:

The IF statement does not have to be surrounded by a parentheses. However braces { } are required.

if x<y {
  fmt.Println(x+2)
}

If statement can also have an initial short statement that is executed before the condition. Variable declared inside an if short statement is also available in the else clause

if x := math.Pow(x, n); x < y {
  x = x+2)
} else { 
  x = x - 2
}

Switch

  • Switch in GO does not require a ‘break’ statement in the end of each case. It implicitly runs only on the first selected case and not on all cases that follow.
  • The cases in GO need not be confined to integers alone.
  • Switch cases evaluate from top to bottom and stops when it matches a statement.
  • Switch can also be written without a condition.This evaluates to switch true
func main() {
	fmt.Println("When's Saturday?")
	today := time.Now().Weekday()
	fmt.Println(today + 1)
	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.")
}

Defer

Defer statement defers the execution of a function until all the surrounding functions return. The defer statement is evaluated immediately but the function call is not executed until the surrounding functions return.

func main() {
 defer fmt.Println("lang")
 defer fmt.Println("GO")
 fmt.Println("Welcome")
 fmt.Println("to")
}

Deferred function calls are evaluated and pushed into a stack. The deferred function calls are executed in last-in-first-out order.

Next Post: Go Types (part 1)

Previous Post: Go – Getting Started

2 comments

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s