Ad space (banner)
๐ŸนGo Lessons
Lesson 29 / 68

Higher-Order Functions (Passing a Function as an Argument)

In this lesson you will learn how to pass a function as an argument in Go, so you can treat behaviour itself as a reusable part. This is for anyone searching for "Go higher-order functions how to use".

Passing another function as an argument is what makes something a higher-order function. Picture handing over the rules for a job and letting someone else do the work. Giving a comparison rule to sort.Slice is the classic example.

The sample code sorts in descending order by passing the ordering criterion as an anonymous function, as in sort.Slice(nums, func(i, j int) bool { return nums[i] > nums[j] }). It is a mechanism that shows off how freely Go treats functions as values.

A common stumbling block for beginners is what the comparison function's return value means. Returning true means "put i before j", so the way you write the condition is what decides ascending or descending order.

In real-world development the same idea applies to designs that swap behaviour by situation, and it is exactly how library functions such as sort.Slice are designed.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Go directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)