Skip to content

Instantly share code, notes, and snippets.

@jpbetz
Created October 8, 2024 23:56
Show Gist options
  • Save jpbetz/5bf3b8c4553855ff15afc85da28f754e to your computer and use it in GitHub Desktop.
Save jpbetz/5bf3b8c4553855ff15afc85da28f754e to your computer and use it in GitHub Desktop.
Go lambda hack
package main
import (
"fmt"
)
// An interface can be implemented by a function type definition.
// This can be convenient for allowing inline function declarations
// of interfaces with only a single function.
// Example interface and function type definition:
type I interface {
Func(x int) int
}
type IFunction func(x int) int
func (i IFunction) Func(x int) int {
return i(x)
}
// Example usage:
func Something(x int, a I) int {
return a.Func(x)
}
func main() {
// The function must be cast to the function type, but this can be done inline.
fmt.Printf("%v", Something(10, IFunction(func(x int) int { return x - 1 })))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment