capypad
0 day streak
go / intermediate
Snippet

Custom Function Types for Strategy Pattern

Functions in Go are first-class citizens. You can define custom function types, which is useful for implementing patterns like Strategy or Middleware, allowing behavior to be passed as arguments.

snippet.go
go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package main
 
import "fmt"
 
type Validator func(string) bool
 
func IsEmail(s string) bool {
return len(s) > 3 // Simplified logic
}
 
func ValidateInput(input string, v Validator) {
if v(input) {
fmt.Println("Input is valid")
} else {
fmt.Println("Input is invalid")
}
}
 
func main() {
ValidateInput("[email protected]", IsEmail)
ValidateInput("", func(s string) bool {
return len(s) > 0
})
}
Breakdown
1
type Validator func(string) bool
Defines a new type 'Validator' that represents any function taking a string and returning a bool.
2
func ValidateInput(input string, v Validator)
A function that accepts a Validator type as a parameter.
3
func(s string) bool { ... }
Passes an anonymous function (closure) that matches the Validator signature.