Skip to content

Instantly share code, notes, and snippets.

@AntonStoeckl
Created February 1, 2022 09:58
Show Gist options
  • Save AntonStoeckl/ee2fe2f9c88c3a94c2bde7d1199d5393 to your computer and use it in GitHub Desktop.
Save AntonStoeckl/ee2fe2f9c88c3a94c2bde7d1199d5393 to your computer and use it in GitHub Desktop.
Example for blog post: Go bits: Magic with functions
package closures
// CustomerService has repo as a protperty
// that will be "enclosed" in the receiver methods
type CustomerService struct {
repo CustomerRepository
}
// Register is a receiver method that will be used as a closure
func (s *CustomerService) Register(customerName string) error {
customer := Customer{Name: customerName}
return s.repo.Add(customer)
}
// Remove is a receiver method that will be used as a closure
func (s *CustomerService) Remove(id CustomerID) error {
return s.repo.Delete(id)
}
// ForRegisteringCustomers is a function type
type ForRegisteringCustomers func(customerName string) error
// ForRemovingCustomers is a function type
type ForRemovingCustomers func(id CustomerID) error
// CustomerRegistrationHTTPHandler receives a closure as dependency
// which fullfulls the function type ForRegisteringCustomers
type CustomerRegistrationHTTPHandler struct {
registerCustomer ForRegisteringCustomers
}
// CustomerRemovalHTTPHandler receives a closure as dependency
// which fullfulls the function type ForRegisteringCustomers
type CustomerRemovalHTTPHandler struct {
removeCustomer ForRemovingCustomers
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment