

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Difficulty: 7
click for more info
Not enough gems
Cost: 6 gems
1: Functions
incomplete
2: Multiple Parameters
incomplete
3: Unit Test Lessons
incomplete
4: Declaration Syntax
incomplete
5: Passing Variables by Value
incomplete
6: Ignoring Return Values
incomplete
7: Named Return Values
incomplete
8: The Benefits of Named Returns
incomplete
9: Explicit Returns
incomplete
10: Early Returns
incomplete
11: Functions As Values
incomplete
12: Anonymous Functions
incomplete
13: Defer
incomplete
14: Block Scope
incomplete
15: Processing Orders
incomplete
16: Closures
incomplete
17: Currying
incomplete
Back
ctrl+,
Next
ctrl+.
This lesson's interactive features are locked, please to keep using them
Anonymous functions are true to form in that they have no name. They're useful when defining a function that will only be used once or to create a quick closure.
Let's say we have a function conversions that accepts another function, converter as input:
func conversions(converter func(int) int, x, y, z int) (int, int, int) {
convertedX := converter(x)
convertedY := converter(y)
convertedZ := converter(z)
return convertedX, convertedY, convertedZ
}
We could define a function normally and then pass it in by name... but it's usually easier to just define it anonymously:
func double(a int) int {
return a + a
}
func main() {
// using a named function
newX, newY, newZ := conversions(double, 1, 2, 3)
// newX is 2, newY is 4, newZ is 6
// using an anonymous function
newX, newY, newZ = conversions(func(a int) int {
return a + a
}, 1, 2, 3)
// newX is 2, newY is 4, newZ is 6
}
Complete the printReports function. It takes as input a sequence of messages, intro, body, outro. It should call printCostReport once for each message by making three separate calls (you don't need to use loops or arrays for this).
For each call of printCostReport, give it an anonymous function that returns the cost of a message as an integer. Here are the costs:
Use the built-in len() function to get the length of a string:
helloLen := len("hello")
// helloLen = 5