Functions Flashcards
(16 cards)
What are the four parts of a function declaration in Go?
func keyword, function’s name, input parameters, return type.
How can you simulate optional parameters in Go?
Use structs to pass parameters to a function.
How do you declare variadic input parameters in Go?
Use … before the type in the parameter list.
What is the requirement for using variadic parameters in Go?
Variadic parameters must be the last parameter in the function.
How do you return multiple values in Go?
List types in parentheses, separated by commas.
How do you handle an error when returning multiple values in Go?
Include an error type as one of the return values.
What is the purpose of the _ (underscore) in Go when handling returned values?
It is used to ignore one or more returned values.
What is the function signature in Go?
The function signature includes the number of parameters, types of parameters, and the return type.
How can you assign a function to a variable in Go?
Declare a function variable and assign a function to it using the function’s signature.
What is an anonymous function in Go?
A function without a name, defined inline.
What is a closure in Go?
A function defined inside another function, which can access the outer function’s variables.
How do you pass a function as a parameter in Go?
Pass the function as an argument to another function.
How do you return a function from another function in Go?
Return a closure from the function.
What is the purpose of defer in Go?
It delays the execution of a function until the surrounding function exits, useful for resource cleanup.
How does Go handle function parameters?
Function parameters are passed by value, meaning a copy of the value is used. Maps and slices are exceptions, as they are passed by reference.
How does Go handle maps and slices when passed as function parameters?
Maps can modify key-value pairs, and slices can modify elements but cannot change their length.