Look at this Go function that returns two values. What will be printed?
package main import "fmt" func divide(a, b int) (int, int) { return a / b, a % b } func main() { q, r := divide(10, 3) fmt.Println(q, r) }
Remember that the first return value is the quotient and the second is the remainder.
The function divides 10 by 3. The quotient is 3 and the remainder is 1, so it prints "3 1".
What will this program print?
package main import "fmt" func getValues() (int, string) { return 42, "hello" } func main() { val, _ := getValues() fmt.Println(val) }
The underscore (_) is used to ignore a return value.
The second return value is ignored using _, so only 42 is printed.
Check the named return values and what the function returns.
package main import "fmt" func swap(x, y int) (a int, b int) { a = y b = x return } func main() { a, b := swap(5, 10) fmt.Println(a, b) }
Named return values can be returned by just using return without arguments.
The function swaps the values by assigning named returns and returns them implicitly, so output is "10 5".
What error will this code cause?
package main func foo() (int, int) { return 1 } func main() {}
Check the number of values returned compared to the function signature.
The function expects two return values but only returns one, causing a type mismatch error.
Analyze this function signature and tell how many values it returns and their types.
func process(data []int) (sum int, avg float64, err error) { // implementation omitted return }
Look at the named return values and their types carefully.
The function returns three values: sum (int), avg (float64), and err (error).