Functions in Go
A function in Go is a reusable block of code that performs a specific task. Functions help you organize logic, avoid repetition, and make programs easier to read and maintain.
In real applications, functions are used to calculate values, process data, validate inputs, and perform operations repeatedly.
Why Functions Are Important
- Reduce code duplication
- Improve readability
- Make programs modular
- Simplify debugging and testing
Basic Function Syntax
A function in Go is declared using the func keyword.
func functionName(parameters) returnType {
// function body
}
Simple Function Example
The following function prints a welcome message.
package main
import "fmt"
func greet() {
fmt.Println("Welcome to Go Programming")
}
func main() {
greet()
}
Here, the greet function is called from main().
Functions with Parameters
Functions can accept parameters to work with dynamic data.
package main
import "fmt"
func printSquare(number int) {
fmt.Println("Square:", number*number)
}
func main() {
printSquare(6)
}
The function receives a number and prints its square.
Functions with Return Values
Functions can return values using the return keyword.
package main
import "fmt"
func add(a int, b int) int {
return a + b
}
func main() {
result := add(25, 40)
fmt.Println("Total:", result)
}
The function calculates the sum of two numbers and returns the result.
Real-World Example: Salary Calculation
This example calculates monthly salary after tax deduction.
package main
import "fmt"
func calculateSalary(base int, tax int) int {
return base - tax
}
func main() {
salary := calculateSalary(50000, 7000)
fmt.Println("Final Salary:", salary)
}
Functions allow you to reuse salary logic across the application.
Multiple Parameters of Same Type
You can shorten parameter types when multiple parameters share the same type.
func multiply(a, b int) int {
return a * b
}
Calling Functions Multiple Times
Functions can be reused as many times as needed.
package main
import "fmt"
func area(length, width int) int {
return length * width
}
func main() {
fmt.Println("Room 1 Area:", area(10, 12))
fmt.Println("Room 2 Area:", area(8, 9))
}
This avoids repeating area calculation logic.
Function Naming Best Practices
- Use clear, descriptive names
- Start with lowercase for private functions
- Use verbs for actions (calculate, print, get)
Common Mistakes
- Forgetting to return a value
- Mismatching parameter types
- Unused parameters
When to Use Functions
- Repeating logic
- Processing real-world data
- Performing calculations
- Organizing large programs
What’s Next?
In the next lesson, you will learn about Multiple Return Values in Go, a powerful feature that allows functions to return more than one result.