본문 바로가기
Go

[Go] Control Flow

by llHoYall 2021. 10. 10.

Like the other languages, Go has a similar syntax for control flow.

Conditional Statement

if Statement

if CONDITION {
  STATEMENTS
} else if CONDITION {
  STATEMENTS
} else {
  STATEMENTS
}

Definitely, you know, if statements are executed only if the conditions are true.

else if and else statements can be omitted.

In addition, if statement can be nested.

package main

import "fmt"

func main() {
  score := 80

  if score == 100 {
    fmt.Println("A")
  } else if score >= 90 {
    fmt.Println("B")
  } else if score >= 80 {
    fmt.Println("C")
  } else if score >= 70 {
    fmt.Println("D")
  } else {
    fmt.Println("F")
  }
}

Go also supports short-circuit conditions.

Namely. when you use && or || operator as a condition, the following conditions are ignored by the preceding conditions.

 

You can use the initial statement in if condition.

if INITIAL; CONDITION {
  STATEMENTS
}
func getNumber() int {
  return 3
}

func main() {
  if a := getNumber(); a >= 0 {
    fmt.Println("Positive")
  } else {
    fmt.Println("Negative")
  }
  // fmt.Println(a)	=> Error!
}
// Positive

The scope of the variable initialized in the if statement is limited by the if statement.

switch Statement

switch EXPRESSION {
  case EXPRESSION1,...:
    STATEMENTS
  case EXPRESSION2,...:
    STATEMENTS
  ...
  default:
    STATEMENTS
}
for id := 0; id <= 3; id++ {
  switch id {
  case 1:
    fmt.Println("ID: 1")
  case 2:
    fmt.Println("ID: 2")
  default:
    fmt.Println("Wrong ID!")
  }
}
// Wrong ID!
// ID: 1
// ID: 2
// Wrong ID!

Unlike other languages, Go doesn't have to specify break in the switch statement.

Then, how can we execute multiple cases?

id := 1
switch id {
  case 1:
    fmt.Println("ID: 1")
    fallthrough
  case 2:
    fmt.Println("ID: 2")
  default:
    fmt.Println("Wrong ID!")
}
// ID: 1
// ID: 2

If you use the fallthrough keyword, it executes the next cases as well.

day := "fri"
switch day {
case "mon", "wed":
  fmt.Println("Study Math")
case "tue", "thu":
  fmt.Println("Study Eng")
case "fri":
  fmt.Println("Study Music")
default:
  fmt.Println("Play Fun")
}
// Study Music

You can put multiple values in a single case.

floor := 7
switch {
case floor < 10:
  fmt.Println("Low")
case floor >= 10:
  fmt.Println("High")
default:
  fmt.Println("I's impossible")
}
// Low

You can omit the expression in the switch statement.

 

switch statement is also able to use initial statement the same as if statement.

switch INITIAL; EXPRESSION {
  ...
}
func getNumber() int {
  return 1
}

func main() {
  switch a := getNumber(); a {
  case 1:
    fmt.Println("1")
  case 2:
    fmt.Println("2")
  default:
    fmt.Println("Too big")
}
// 1

Loop Statement

for Statement

Go has only for statements as a loop statement.

for loop is similar to other languages like C/C++, Java, or JavaScript.

for INITIALIZATION; CONDITION; POSTPROCESS { }
package main

import (
  "fmt"
)

func main() {
  for x := 0; x < 5; x++ {
    fmt.Println(x)
  }
}
// 0
// 1
// 2
// 3
// 4

The post-process of Go's for statement doesn't allow the pre-increment or pre-decrement.

It allows only post-increment or post-decrement.

Infinite Loop

You can omit the initialization, condition, or post-process.

If you omit the initialization and post-process, it is similar to while loop in other languages. But, in this case, you cannot omit the semicolon(;).

If you omit the condition as well, it is the same as the condition true.

So if you want an infinite loop, just write for with omitting all other things.

for {  // same as the "for true {"
  // infinite execute
}

continue and break

When reaching continue, it starts the next loop without executing the codes below.

for i := 0; i < 10; i++ {
  fmt.Print(i, ": ")
  if i >= 5 {
    continue
  }
  fmt.Println("OK")
}
// 0: OK
// 1: OK
// 2: OK
// 3: OK
// 4: OK
// 5: 6: 7: 8: 9: 

When reaching break, it exits the current loop immediately.

i := 0
for {
  fmt.Println("Before: ", i)
  if i == 3 {
    break
  }
  ++i
  fmt.Println("After: ", i)
}
fmt.Println("End")
// Before: 0
// After: 1
// Before: 1
// After: 2
// Before: 2
// After: 3
// Before: 3
// End

Label with Nested for Loop

If you use the label, you can easily escape from the nested loop.

func main() {
NestedFor:
  for i := 1; i < 3; i++ {
    for j := 1; j < 3; j++ {
      fmt.Printf("%d * %d = %d\n", i, j, i*j)
      if i == 2 && j == 2 {
        break NestedFor
      }
    }
  }
}
// 1 * 1 = 1
// 1 * 2 = 2
// 2 * 1 = 2
// 2 * 2 = 4

Labels are convenient, but not recommended.

Because it makes a code harder to read, therefore it may cause an unexpected bug.

range-for Statement

You can use a range-for statement with an array or map types.

var arrData []int = []int{3, 6, 9}
for i, v := range arrData {
  fmt.Println(i, v)
}
// 0 3
// 1 6
// 2 9

var mapData map[int]string = map[int]string{
  1: "one",
  2: "two",
  3: "three",
}
for k, v := range mapData {
  fmt.Println(k, v)
}
// 1 one
// 2 two
// 3 three

'Go' 카테고리의 다른 글

[Go] Structure  (0) 2021.10.11
[Go] Array  (0) 2021.10.10
[Go] Constant  (0) 2021.10.05
[Go] The Error of Floating Point Number  (0) 2021.10.04
[Go] Operator  (0) 2021.10.04

댓글