Junior — Middle
How can you manage program behavior during its execution in Go?
sobes.tech AI
Answer from AI
In the Go language, program behavior during runtime can be controlled in several ways:
- Conditional statements (
if,switch) — allow executing different blocks of code depending on conditions. - Loops (
for) — for repeating actions. - Error handling using return values and the
if err != nilconstruct. - Panic and recover (
panicandrecover) — for handling critical errors and recovering from them. - Goroutines and channels — for managing concurrency and synchronization.
- Interfaces and polymorphism — for changing behavior through different implementations.
Example of using a conditional statement and error handling:
if err := doSomething(); err != nil {
fmt.Println("Error:", err)
return
}
if value > 10 {
fmt.Println("Value is greater than 10")
} else {
fmt.Println("Value is 10 or less")
}