Skip to content

Instantly share code, notes, and snippets.

@AntonStoeckl
Created February 1, 2022 09:56
Show Gist options
  • Save AntonStoeckl/7ba1238136449b67d40385caae2302a0 to your computer and use it in GitHub Desktop.
Save AntonStoeckl/7ba1238136449b67d40385caae2302a0 to your computer and use it in GitHub Desktop.
Example for blog post: Go bits: Magic with functions
package closures_test
import (
"testing"
"github.com/matryer/is"
. "go-bits/magic-with-functions/closures"
)
func Test_object_with_receiver_method_as_closure(t *testing.T) {
// ARRANGE
shouldBe := is.New(t)
repo := NewFileBasedCustomerRepository()
// the repo from above is a property of the CustomerService struct
// which is "enclosed" in the method closures below
service := NewCustomerService(repo)
// this is a receiver method used as a value
register := service.Register
// we are passing this method as a closure
registrationHandler := NewCustomerRegistrationHTTPHandler(register)
// this is a receiver method used as a value
remove := service.Remove
// we are passing this method as a closure
removalHandler := NewCustomerRemovalHTTPHandler(remove)
// ACT
registerErr := registrationHandler.Handle("John Doe")
// ASSERT
shouldBe.NoErr(registerErr)
// CLEAN UP
removalErr := removalHandler.Remove(CustomerID{Value: "123435"})
shouldBe.NoErr(removalErr)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment