Control flow with if

package main

import (
        "fmt"
)

func main() {
        comment := map[string]string{
                "route53":       "Love it",
                "s3":            "",
                "ec2":           "oh!",
                "Snowball Edge": "Urban Dictionary both of those words.",
                "fargate":       "Sounds clever, but nobody will know what it does.",
                "graviton":      "Terrific if the next word in the product name is 'bomb'",
        }

        // Uncomment one on these three lines
        name := "ec2"
        // name := "route53"
        // name := "s3"

        if len(comment[name]) > 4 {
                fmt.Println("Clever comment for: ", name, " - ", comment[name])
        } else if len(comment[name]) > 0 {
                fmt.Println("Short comment for: ", name)
        } else {
                fmt.Println("No comment for: ", name)
        }

}
  1 package main
  2
  3 import (
  4         "fmt"
  5 )
  6
  7 func main() {
  8         comment := map[string]string{
  9                 "route53":       "Love it",
 10                 "s3":            "",
 11                 "ec2":           "oh!",
 12                 "Snowball Edge": "Urban Dictionary both of those words.",
 13                 "fargate":       "Sounds clever, but nobody will know what it does.",
 14                 "graviton":      "Terrific if the next word in the product name is 'bomb'",
 15         }
 16
 17         // Uncomment one on these three lines
 18         name := "ec2"
 19         // name := "route53"
 20         // name := "s3"
 21
 22         if len(comment[name]) > 4 {
 23                 fmt.Println("Clever comment for: ", name, " - ", comment[name])
 24         } else if len(comment[name]) > 0 {
 25                 fmt.Println("Short comment for: ", name)
 26         } else {
 27                 fmt.Println("No comment for: ", name)
 28         }
 29
 30 }
 

Uncomment one of the lines 18,19,20 and run the program.

So there are not many surprises with if:

 22         if len(comment[name]) > 4 {
 23                 fmt.Println("Clever comment for: ", name, " - ", comment[name])
 24         } else if len(comment[name]) > 0 {
 25                 fmt.Println("Short comment for: ", name)
 26         } else {
 27                 fmt.Println("No comment for: ", name)
 28         }
  • the boolean expression has no brackets
  • the left curly bracket has to be on the same line as the if { has
  • an else-if is just another if

Multiple if-else statements can be written with the switch statement. This is described in the next chapter.

See also

Source

See the full source on github.

Sources