Created
August 3, 2024 19:38
-
-
Save yuri-potatoq/627a9113dd703c484e7527d2f3a4773f to your computer and use it in GitHub Desktop.
Builder Pattern in Go only with functions
This file contains hidden or 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" | |
type StructuredMessage struct { | |
Kind string | |
Details map[string]any | |
} | |
type BuildFunc[T any] func() *T | |
type ApplyFunc[T any] func(string, map[string]any) (ApplyFunc[T], BuildFunc[T]) | |
func NewErrorBuilder(kind string) (ApplyFunc[StructuredMessage], BuildFunc[StructuredMessage]) { | |
var applyF ApplyFunc[StructuredMessage] | |
target := &StructuredMessage{Kind: kind, Details: make(map[string]any)} | |
buildF := func() *StructuredMessage { | |
return target | |
} | |
applyF = func(kind string, detail map[string]any) (ApplyFunc[StructuredMessage], BuildFunc[StructuredMessage]) { | |
target.Details[kind] = detail | |
return applyF, buildF | |
} | |
return applyF, buildF | |
} | |
func main() { | |
with, build := NewErrorBuilder("messages") | |
with, build = with("error", map[string]any{"type": "unrecoverable"}) | |
r := build() | |
fmt.Printf("Result: %+v\n", r) | |
// OUT: | |
// Result: &{Kind:messages Details:map[error:map[type:unrecoverable]]} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment