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]
More Related questions...