Search code examples
goclosures

How does a function called in Go, get the access to calling functions parameters?


See code for reference https://go.dev/play/p/yIG2B6DKcoc (also pasted here):

As in this piece of code - the parameter order is not passed to sort.Slice() function, yet it gets printed fine in the called Less() method of sort package.

What is the property that enables this?

package main

import (
    "fmt"
    "sort"
)

func main() {
    order := "abcd"
    s := "bca"
    fmt.Printf("ans: %v\n", customSortString(order, s))
}

func customSortString(order string, s string) string {
    sort.Slice([]byte(s), func(a, b int) bool {
        fmt.Printf("order: %v\n", order) // <------ How does this work? order is not passed to sort.Slice() function. 
        return s[a] < s[b]
    })
    return ""
}

Solution

  • https://go.dev/ref/spec#Function_literals:

    Function literals are closures: they may refer to variables defined in a surrounding function. Those variables are then shared between the surrounding function and the function literal, and they survive as long as they are accessible.