Skip to content

Instantly share code, notes, and snippets.

@ObsidianCat
Last active July 30, 2023 10:45
Show Gist options
  • Save ObsidianCat/2be44ef1426434ca706384bc2ae7a40e to your computer and use it in GitHub Desktop.
Save ObsidianCat/2be44ef1426434ca706384bc2ae7a40e to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
)
type steps struct {
dayOfTheWeek string
greeting string
tasks []string
funcs []stepFunc
}
type stepFunc func() error
func (s *steps) Next(f stepFunc) *steps {
s.funcs = append(s.funcs, f)
// return the step func to allow for chaining
return s
}
func (s *steps) Do() error {
for _, f := range s.funcs {
if err := f(); err != nil {
// stop the chain prematurely
return err
}
}
return nil
}
func (s *steps) startTheDay() error {
// chekc if valid day of the week
if s.dayOfTheWeek == "" {
return fmt.Errorf("day of the week is not set")
}
fmt.Println("Hello " + s.dayOfTheWeek)
return nil
}
func (s *steps) doTasks() error {
fmt.Println("Today's tasks are:")
for _, task := range s.tasks {
fmt.Println(task)
}
return nil
}
func main() {
// create a new steps struct
s := &steps{
dayOfTheWeek: "Monday",
greeting: "Hello",
tasks: []string{
"Run",
"Swim",
"Cycle",
},
}
// chain the steps together and execute them
err := s.Next(s.startTheDay).Next(s.doTasks).Do()
if err != nil {
fmt.Println(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment