Golang / GoLang Basics Interview Questions
How are functions defined in Go? What are variadic functions and named return values?
Functions are first-class citizens in Go — they can be assigned to variables, passed as arguments, and returned from other functions. Go functions support multiple return values (the primary mechanism for error handling), named returns, and variadic parameters.
// Basic function with multiple return values
func divide(a, b float64) (float64, error) {
if b == 0 { return 0, errors.New("division by zero") }
return a / b, nil
}
// Named return values — document what is returned
// Use sparingly; best for short functions only
func minMax(nums []int) (min, max int) {
min, max = nums[0], nums[0]
for _, n := range nums[1:] {
if n < min { min = n }
if n > max { max = n }
}
return // naked return — returns named values min and max
}
// Variadic function — accepts 0 or more arguments of the given type
func sum(nums ...int) int {
total := 0
for _, n := range nums { total += n }
return total
}
sum(1, 2, 3) // 6
s := []int{4, 5, 6}
sum(s...) // 15 — spread a slice with ...
// Function as a value (first-class)
double := func(n int) int { return n * 2 }
fmt.Println(double(7)) // 14
// Higher-order function
func apply(nums []int, f func(int) int) []int {
result := make([]int, len(nums))
for i, v := range nums { result[i] = f(v) }
return result
}
fmt.Println(apply([]int{1, 2, 3}, double)) // [2 4 6]
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
