Functions help organize code into small tasks. Understanding how they run step-by-step makes your programs work correctly.
0
0
Function execution flow in Go
Introduction
When you want to repeat a task many times without writing code again.
When you want to break a big problem into smaller, easier parts.
When you want to reuse code in different places.
When you want to make your program easier to read and fix.
Syntax
Go
func functionName(parameters) returnType {
// code to run
return value
}Functions start running from the first line inside the curly braces.
When a function finishes, it sends back a result with return or just ends if no return is needed.
Examples
A simple function that prints a message and does not return anything.
Go
func greet() {
fmt.Println("Hello!")
}A function that takes two numbers, adds them, and returns the result.
Go
func add(a int, b int) int { return a + b }
Calling functions in order: first print greeting, then add numbers and print the sum.
Go
func main() {
greet()
sum := add(3, 4)
fmt.Println(sum)
}Sample Program
This program shows how functions run one after another. First, greet prints a message. Then, add calculates the sum of 5 and 7, and the result is printed.
Go
package main import "fmt" func greet() { fmt.Println("Hello, friend!") } func add(a int, b int) int { return a + b } func main() { greet() result := add(5, 7) fmt.Println("Sum is", result) }
OutputSuccess
Important Notes
Functions run in the order they are called inside main or other functions.
If a function has a return value, you can save it in a variable to use later.
Functions help keep your code clean and easy to understand.
Summary
Functions run their code from top to bottom when called.
They can return values to send results back.
Understanding the flow helps you write programs that do tasks step-by-step.