Go Functions

Go Functions – Complete Tutorial
In Go (Golang), a function is a reusable block of code that performs a specific task.
They are the backbone of Go programs and are heavily used in APIs, microservices, and system programs.
What is a Function in Go?
A function:
Groups logic into a reusable unit
Improves readability & maintainability
Helps in modular programming
In Go, functions are first-class citizens.
Basic Function Syntax
Example
Function with Parameters
Function with Return Value
Multiple Parameters with Same Type
- Cleaner syntax
- Interview favorite
Multiple Return Values (Go Special Feature)
Call:
Widely used for error handling
Named Return Values
- Optional
- Use carefully (clarity first)
Function Returning Error (Real-Life)
Very important interview topic
Anonymous Functions
With variable:
Functions as Parameters
Foundation of functional programming
Variadic Functions
Accept variable number of arguments.
Pass by Value vs Reference
Pass-by Value (Default)
Pass by Reference (Pointer)
Go passes everything by value, but pointers allow modification.
Function Scope
Variables inside function are local
Not accessible outside
x not accessible outside
Common Mistakes
- _Forgetting return type
- Ignoring returned error
- Confusing pointers
- Overusing named returns
Interview Questions & MCQs
Q1. Can Go functions return multiple values?
A) Yes
B) No
Answer: A
Q2. How are parameters passed in Go?
A) By reference
B) By value
Answer: B
Q3. Which is used for error handling in Go functions?
A) try-catch
B) panic only
C) return error
D) throws
Answer: C
Q4. What is a variadic function?
A) Function with no return
B) Function with many returns
C) Function with variable arguments
D) Recursive function
Answer: C
Q5. Are functions first-class in Go?
A) Yes
B) No
Answer: A
Real-Life Use Cases
- REST API handlers
- Business logic modules
- Utility helpers
- Microservices
- System tools
Summary
Function are core building blocks in Go
Support parameters, return values & errors
Go allows multiple return values
Variadic & anonymous functions are powerful
Error handling via return values
Must-know topic for Go interviews
