Chapter 41: Go Functions

Go: Functions.

Functions are the building blocks of every real Go program. Once you understand how to write, call, and organize functions in Go, you can start building actual useful tools, APIs, CLI apps, servers — everything.

Go functions are very clean, very explicit, very safe, and have some unique features that make them feel elegant compared to other languages.

Let’s go through everything like we’re pair-programming together — slowly, with many copy-paste examples, style notes, common patterns, gotchas, and real-world usage.

1. Basic Syntax – The Anatomy of a Go Function

Go

Key parts:

  • func keyword
  • name starts with uppercase → exported (public, visible outside package)
  • name starts with lowercase → unexported (private to package)
  • parameters: name first, then type (opposite of C++/Java)
  • return type(s) after parentheses
  • multiple return values are very common (especially with errors)
  • braces {} always required (even for one line)

2. Simple Examples – Start Here

Go

3. Named Return Values (Very Powerful & Idiomatic)

When you name the return values, they are automatically initialized to zero value and you can use naked return (return with no values).

Go

Why named returns are loved:

  • Very common in error handling + multiple returns
  • Acts like “early named exit points”
  • Makes signature self-documenting

4. Multiple Return Values – The Go Way

Go

Blank identifier _ is used when you want to ignore a return value.

5. Variadic Functions (… – variable number of arguments)

Go

Only one variadic parameter and it must be last.

6. Functions as Values (First-class citizens)

Go

7. Anonymous Functions & Closures

Go

8. Best Practices & Common Patterns (2025–2026 style)

  • Short functions – aim for < 30–40 lines
  • Single responsibility – one function = one job
  • Return early on errors
  • Use named returns when there are 2+ return values
  • Pass slices/maps by value (cheap – header copy)
  • Use pointers only when you need to modify receiver or avoid copy cost
  • Variadic + slice – most common variadic pattern

9. Quick Practice – Try Writing These

  1. Function that takes two numbers and returns sum, difference, product
  2. Function that returns (min, max) of a slice of ints
  3. Variadic function that concatenates strings with separator
  4. Closure that generates next Fibonacci number each call

Which function felt most natural to write?

Any part still confusing?

  • Multiple returns vs single return + error struct?
  • When to use named vs unnamed returns?
  • Closures capturing variables – lifetime rules?
  • Or ready for structs next?

Keep writing small functions — once you feel comfortable calling them, returning multiple values, and using closures, you’ll be able to build real programs very quickly.

You’re doing awesome — keep going! 💪🇮🇳🚀

You may also like...

Leave a Reply

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