Golang / GoLang Basics Interview Questions
How do if, for, and switch statements work in Go?
Go has a deliberately minimal set of control-flow constructs. There is only one loop keyword — for — which covers everything a while, do-while, and classic for loop does in other languages.
// if with an init statement â err is only in scope inside the if block if err := doWork(); err != nil { log.Fatal(err) } // for â C-style for i := 0; i < 5; i++ { fmt.Println(i) } // for as while n := 1 for n < 128 { n *= 2 } // for â infinite loop (use break or return to exit) for { if done() { break } doWork() } // for range â slices, maps, strings, channels fruits := []string{"apple", "banana", "cherry"} for i, fruit := range fruits { fmt.Printf("%d: %s\n", i, fruit) } for _, fruit := range fruits { fmt.Println(fruit) } // ignore index // switch â no implicit fallthrough switch day { case "Sat", "Sun": fmt.Println("Weekend") case "Mon", "Tue", "Wed", "Thu", "Fri": fmt.Println("Weekday") default: fmt.Println("Unknown") } // switch with no expression â replaces long if-else chains switch { case score >= 90: fmt.Println("A") case score >= 80: fmt.Println("B") default: fmt.Println("C or below") }
More Related questions...