Functions are first-class values in Go. Multiple return values are idiomatic—especially (result, error) pairs instead of exceptions like Java.
Syntax and multiple returns
func add(a, b int) int {
return a + b
}
func div(a, b int) (int, error) {
if b == 0 {
return 0, fmt.Errorf("divide by zero")
}
return a / b, nil
}
Named result parameters (func f() (n int, err error)) are allowed—use sparingly for clarity.
Variadic and deferred calls
func sum(nums ...int) int accepts zero or more ints. Functions can be assigned to variables and passed as arguments—enabling simple functional patterns.
Important interview questions and answers
- Q: Multiple return values?
A: Common for results plus errors; callers must handle or ignore explicitly—no hidden exceptions. - Q: Exported function names?
A: Capitalized names are exported (public) across packages; lowercase names are package-private.
Self-check
- How do you return two values from a function?
- What makes a function name exported?
Pitfall: Ignoring the error return with _ hides failures—handle or wrap errors explicitly, unlike unchecked exceptions in Java.
Interview prep
- Multiple returns?
Common pattern—especially
(result, error); callers must handle explicitly.- Exported names?
Capitalized identifiers are exported from a package; lowercase are package-private.