Consider the following Go code. What will be printed when main runs?
package main import "fmt" func divideAndRemainder(a, b int) (int, int) { return a / b, a % b } func main() { q, r := divideAndRemainder(17, 5) fmt.Println(q, r) }
Remember that / is integer division and % is remainder.
The function returns the quotient and remainder of dividing 17 by 5. 17 divided by 5 is 3 with remainder 2, so the output is 3 2.
Look at this Go function and its call. What is the output?
package main import "fmt" func greet(name string) string { return "Hello, " + name + "!" } func main() { message := greet("Alice") fmt.Println(message) }
Check the string concatenation and punctuation.
The function returns the greeting string with a comma and exclamation mark exactly as shown, so the output is Hello, Alice!.
Analyze this Go code using named return values. What will it print?
package main import "fmt" func swap(a, b int) (x int, y int) { x = b y = a return } func main() { a, b := 10, 20 x, y := swap(a, b) fmt.Println(x, y) }
Named return values can be returned by just return without arguments.
The function swaps the values by assigning to named return variables and returns them implicitly. So output is 20 10.
What error will occur when running this Go code?
package main func add(a, b int) int { return a + b return a - b } func main() {}
Check if code after a return statement is allowed.
In Go, code after a return statement in the same block is unreachable, causing a syntax error.
Consider this Go function signature. How many values does it return?
func process(data []int) (result int, err error)
Look at the parentheses and types in the return signature.
The function returns two values: an int named result and an error named err.