# Go learning note 03 - structure control

Catalog

## Conditional statement

Condition statements use the if keyword to determine conditions, such as:

```    func bounded(v int) int {
if v > 100 {
return 100
} else if v < 0 {
return 0
} else {
return v
}
}```

Judgment conditions are not enclosed in parentheses

The value can be assigned in the judgment condition, and the scope of the assignment variable is limited to this if statement block.

switch Statements

```func grade(score int) string {
g := ""
switch {
case score < 0 || score > 100:
//When a program fails, panic interrupts the program
panic(fmt.Sprintf(
"Wrong score: %d", score))
case score < 60:
g = "F"
case score < 80:
g = "C"
case score < 90:
g = "B"
case score <= 100:
g = "A"
}
return g
}```

In Go language, case doesn't end with break.
After the switch, there can be no conditions, and condition judgment can be performed after the case.

## Loop statement

Code example:

```    sum := 0
for i:= 1;i <= 100 ;i++ {
sum += i
}
```
• The conditions of the for statement do not need to be enclosed in parentheses
• Initial condition, end condition and increasing expression can be omitted
```package main

import(
"bufio"
"fmt"
"os"
"strconv"
)

func convertToBin(n int) string {
bin := ""
//Omit the initial condition, equivalent to the while statement
for ; n > 0; n /= 2{
lsb := n % 2
bin = strconv.Itoa(lsb) + bin
}
return bin
}

file, err := os.Open(filename)

if err != nil{
panic(err)
}

scanner := bufio.NewScanner(file)

for scanner.Scan(){
fmt.Println(scanner.Text())
}
}

func main() {
fmt.Println(convertToBin(13),
convertToBin(5))