[Solved] i don’t understand the code : result = quote123(func(x int) string { return fmt.Sprintf(“%b”, x) })


quote123 accepts any function that takes an integer argument and returns a string. The argument passed to it in this code is a function literal, also known as an enclosure or an anonymous function, with this signature. The function literal has two parts:

func(x int) string

This is the signature of the functional literal. This shows you that it matches the argument type taken by quote123, which is the type convert, a named type defined as type convert func(int) string

{ return fmt.Sprintf("%b", x) }

This is the body, or implementation, of the function literal. This is the code actually run when the function literal is called. In this case, it takes the integer x, formats it in binary (that’s what the %b formatting verb does) as a string, and returns that string.

quote123 takes this function as an argument, calls it with an integer (in this case, the integer 123), then takes the string return by it and formats it using the %q formatting verb, which surrounds the given strings in quotations.

The net effect of this is 123 is passed in, formatted as binary (1111011), returned as a string (1111011), then formatted again with surrounding quotes ("1111011") which is then ultimately printed out to console.

Accepting a function literal like this allows you to customize behavior when calling a function. quote123 will always return a quoted string, but what’s in that can change. For example, if I instead gave it the following literal:

func(x int) string { return fmt.Sprintf("%06d", x) }

I would get back the string "000123", because the formatting verb %06d says to print it as an integer, with width 6, and pad it with 0’s instead of space characters. If I instead used:

func(x int) string { return "hello world" }

I would always get back the string "hello world", regardless of which integer it was called with.

3

solved i don’t understand the code : result = quote123(func(x int) string { return fmt.Sprintf(“%b”, x) })