Last active
July 30, 2023 10:45
-
-
Save ObsidianCat/2be44ef1426434ca706384bc2ae7a40e to your computer and use it in GitHub Desktop.
This file contains 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 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