Go Functions
Building reusable blocks of code in Go
🔧 What are Go Functions?
Functions in Go are reusable blocks of code that perform specific tasks. They help organize code, avoid repetition, and make programs more modular and maintainable.
// This is a simple Go function example
func greet() {
fmt.Println("Hello, World!")
}
func main() {
greet() // Call the function
}
Output:
Hello, World!
Key Function Concepts
Declaration
Use 'func' keyword to declare functions
func functionName() {
// code here
}
Calling
Execute functions by calling their name
functionName() // Call function
Return Values
Functions can return values
func add() int {
return 5 + 3
}
Purpose
Organize and reuse code efficiently
func calculate() {
// Reusable logic
}
🔹 Basic Function Structure
Every Go function follows this basic structure:
package main
import "fmt"
// Function declaration
func sayHello() {
fmt.Println("Hello from function!")
}
func main() {
sayHello() // Function call
}
Output:
Hello from function!
🔹 Functions with Return Values
Functions can return values to the caller:
package main
import "fmt"
// Function that returns an integer
func getNumber() int {
return 42
}
// Function that returns a string
func getName() string {
return "Go Programming"
}
func main() {
number := getNumber()
name := getName()
fmt.Println("Number:", number)
fmt.Println("Name:", name)
}
Output:
Number: 42
Name: Go Programming
🔹 Function Examples
Here are some practical function examples:
package main
import "fmt"
// Function to calculate area of rectangle
func calculateArea() int {
length := 10
width := 5
return length * width
}
// Function to display a message
func showMessage() {
fmt.Println("Welcome to Go Functions!")
}
// Function to check if number is even
func isEven() bool {
number := 8
return number%2 == 0
}
func main() {
area := calculateArea()
fmt.Println("Area:", area)
showMessage()
even := isEven()
fmt.Println("Is even:", even)
}
Output:
Area: 50
Welcome to Go Functions!
Is even: true