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")
}
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
