laboratory/experiments/go/move/main.go
2022-10-29 23:22:52 +01:00

60 lines
887 B
Go

package main
import (
"fmt"
"strings"
"errors"
"flag"
"os"
)
//go:generate stringer -type=Movement
type Movement int
const (
Unknown Movement = iota
Forward
Backward
Left
Right
)
func newMovement(movement string) (Movement) {
switch strings.ToLower(movement) {
case "forward":
return Forward
case "backward":
return Backward
case "left":
return Left
case "right":
return Right
default:
return Unknown
}
}
func main() {
direction := flag.String("direction", "", "The direction to move.")
flag.Parse()
if err := run(*direction); err != nil {
fmt.Printf("Error: %v.\n", err)
os.Exit(1)
}
}
func run(direction string) error {
if len(direction) == 0 {
return errors.New("direction is not set")
}
move := newMovement(direction)
if move == Unknown {
return errors.New("unknown direction")
}
fmt.Printf("I moved %s.\n", move)
return nil
}