Go Functions #
Functions are blocks of code that perform a specific task and can be called whenever needed. They help you:
- Reuse code
- Organize programs
- Make code more readable
In Go, every program has at least one function: the main()
function. You can also create your own custom functions.
Why Use Functions? #
Functions allow you to break programs into smaller, manageable pieces. They are especially useful when you need to:
- Perform the same operation multiple times
- Pass data between different parts of your program
- Return results from computations
Quick Examples #
1. Simple Function #
package main
import "fmt"
func greet() {
fmt.Println("Hello, Go Functions!")
}
func main() {
greet()
}
Output:
Hello, Go Functions!
2. Function with Parameters #
package main
import "fmt"
func greet(name string) {
fmt.Printf("Hello, %s!\n", name)
}
func main() {
greet("Alice")
greet("Bob")
}
Output:
Hello, Alice!
Hello, Bob!
3. Function with Return Value #
package main
import "fmt"
func add(a int, b int) int {
return a + b
}
func main() {
sum := add(5, 7)
fmt.Println(sum)
}
Output:
12
4. Recursive Function #
package main
import "fmt"
func factorial(n int) int {
if n == 0 {
return 1
}
return n * factorial(n-1)
}
func main() {
fmt.Println(factorial(5))
}
Output:
120
Functions are fundamental in Go. Mastering them will make your programs modular, efficient, and easier to read.