Go Tutorial
Estimated reading: 4 minutes 42 views

🧰 Go Function Basics – Parameters, Recursion, Closures, Methods & More

🧲 Introduction – Why Functions Matter in Go

Functions in Go are more than just reusable blocks of code—they’re first-class citizens. You can pass them as values, define them anonymously, use closures, and even attach them to structs as methods. Go’s function model is powerful, yet simple.

🎯 In this guide, you’ll learn:

  • How to declare and use functions in Go
  • Difference between call by value and reference
  • Anonymous functions and closures
  • Go method functions on structs
  • Recursion and the defer keyword

📘 Topics Covered

🔹 Concept📖 Description
🔧 Go Function BasicsFunction syntax, parameters, return types
📥 Go Call by ValueArguments passed by copying the value
📤 Go Call by ReferencePassing pointers for memory-safe modification
🎯 Go Functions as ValuesAssigning functions to variables or passing them as arguments
🧑‍🎤 Go Anonymous FunctionsFunctions without names, often inline
🔒 Go Function ClosuresFunctions capturing outer scope variables
🧍 Go Method FunctionsFunctions associated with struct types
🔁 Go RecursionCalling a function from itself
🕗 Go defer KeywordPostponing a statement until surrounding function returns

🔧 Go – Function Basics

func add(a int, b int) int {
    return a + b
}

func main() {
    result := add(2, 3)
    fmt.Println("Sum:", result)
}

✅ Multiple returns:

func split(sum int) (int, int) {
    return sum / 2, sum % 2
}

📥 Go – Call by Value

func update(val int) {
    val = val + 10
}

func main() {
    num := 5
    update(num)
    fmt.Println(num) // 5 (unchanged)
}

🧠 Go passes basic types by value. Original variable is not affected.


📤 Go – Call by Reference (Pointers)

func update(val *int) {
    *val = *val + 10
}

func main() {
    num := 5
    update(&num)
    fmt.Println(num) // 15
}

✅ Use pointers (*, &) to modify the original variable.


🎯 Go – Functions as Values

func greet(name string) string {
    return "Hello " + name
}

func main() {
    f := greet
    fmt.Println(f("Gopher"))
}

✅ Functions can be:

  • Assigned to variables
  • Passed as arguments
  • Returned from other functions

🧑‍🎤 Go – Anonymous Functions

func main() {
    sum := func(a int, b int) int {
        return a + b
    }
    fmt.Println(sum(3, 4))
}

✅ Use for short, inline logic—especially useful in goroutines or callbacks.


🔒 Go – Function Closures

func counter() func() int {
    count := 0
    return func() int {
        count++
        return count
    }
}

func main() {
    inc := counter()
    fmt.Println(inc()) // 1
    fmt.Println(inc()) // 2
}

🧠 Closure remembers the outer variable’s state, even after the outer function exits.


🧍 Go – Method Functions

type User struct {
    name string
}

func (u User) greet() string {
    return "Hi, " + u.name
}

func main() {
    user := User{"Bob"}
    fmt.Println(user.greet())
}

func (receiver Type) methodName()
🔁 Use *Type to modify the original struct.


🔁 Go – Recursion

func factorial(n int) int {
    if n == 0 {
        return 1
    }
    return n * factorial(n-1)
}

✅ Recursive functions must have a base condition to avoid infinite loops.


🕗 Go – defer Keyword

func main() {
    defer fmt.Println("World")
    fmt.Println("Hello")
}

✅ Output:

Hello
World

🧠 defer is useful for:

  • Closing files
  • Unlocking mutexes
  • Cleanup logic

📌 Summary – Recap & Next Steps

Go functions are first-class, flexible, and powerful. With support for pointers, closures, and methods, you can structure code that’s modular, memory-safe, and concurrent-ready.

🔍 Key Takeaways:

  • Functions can return multiple values
  • Use pointers for call-by-reference behavior
  • Anonymous functions and closures add flexibility
  • Structs can have methods with receivers
  • defer runs statements just before a function returns

⚙️ Real-World Use Cases:

  • Handling resources (files, DB) with defer
  • Writing APIs with method-based handlers
  • Using closures for maintaining state in goroutines

❓ Frequently Asked Questions

Can Go functions return multiple values?
✅ Yes. Just list them:

func divide(a, b int) (int, int) {
    return a / b, a % b
}

Is Go pass-by-reference or value?
✅ Go is pass-by-value, but you can simulate reference via pointers (*).


When should I use defer?
✅ Use defer for cleanup logic like closing files or database connections.


Can I define functions inside other functions in Go?
✅ Yes—anonymous or closure functions can be declared inside functions.


What is the difference between function and method in Go?
✅ Functions stand alone, while methods are functions with a receiver (used with structs).


Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

Go – Function Basics

Or Copy Link

CONTENTS
Scroll to Top