0
0
Goprogramming~5 mins

Named return values in Go - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What are named return values in Go?
Named return values are variables defined in a function's signature that hold the return values. They allow you to return values without explicitly specifying them in the return statement.
Click to reveal answer
beginner
How do you declare named return values in a Go function?
You declare named return values by specifying variable names and types inside the parentheses after the function parameters, like: func example() (result int, err error).
Click to reveal answer
intermediate
What happens if you use a bare return statement in a function with named return values?
A bare return returns the current values of the named return variables. This means you don't have to specify the variables explicitly in the return statement.
Click to reveal answer
intermediate
Can named return values improve code readability? Why or why not?
Yes, named return values can improve readability by giving meaningful names to return values, making it clear what each returned value represents without needing extra comments.
Click to reveal answer
beginner
Show a simple Go function using named return values to return the sum and difference of two integers.
Example:
func calc(a, b int) (sum int, diff int) {
    sum = a + b
    diff = a - b
    return
}
This function returns sum and diff without explicitly listing them in the return statement.
Click to reveal answer
In Go, how do you define named return values in a function?
ABy naming variables in the return type parentheses
BBy declaring variables inside the function body
CBy using global variables
DBy using pointers only
What does a bare return statement do in a function with named return values?
AReturns the current values of named return variables
BReturns zero values
CCauses a compile error
DReturns nothing
Which of the following is a benefit of using named return values?
AThey allow multiple return types
BThey improve code readability by naming return values
CThey prevent runtime errors
DThey make functions run faster
What is the output of this Go function? func example() (x int) { x = 5 return } A call to example() returns:
A0
BAn error
C5
DUndefined
Can you mix named and unnamed return values in a Go function signature?
AOnly if the function has one return value
BNo, all must be named or unnamed
COnly in Go versions before 1.10
DYes, but it's discouraged
Explain what named return values are in Go and how they affect the return statement.
Think about how naming return variables changes how you write return statements.
You got /3 concepts.
    Write a simple Go function using named return values to return the quotient and remainder of two integers.
    Use division and modulus operators and name the return values clearly.
    You got /3 concepts.