Created
October 8, 2024 23:56
-
-
Save jpbetz/5bf3b8c4553855ff15afc85da28f754e to your computer and use it in GitHub Desktop.
Go lambda hack
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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