Beginning Programming Lesson 06

Recursion and Error Handling

When I was in college my professor explained recursion as “Pretend you already have a function that does what you need to do.” The problem with that explanation is, it only makes sense after you understand recursion. I think we can do better here. While we are at it, let’s look at error handling too. You can find the code for today’s lesson here. package main import ( "fmt" "log" ) type MinInputError struct { } func (e *MinInputError) Error() string { return "invalid input, number must be greater than 0" } type MaxInputError struct { } func (e *MaxInputError) Error() string { return "invalid input, number must be less than 100" } func Factorial(n int) int { if n == 1 { return n } return n * Factorial(n-1) } func Factorial2(n int) (int, error) { if n < 0 { return 0, &MinInputError{} } if n > 100 { return 0, &MaxInputError{} } ret := n for i := n - 1; i > 0; i-- { ret = ret * i } return ret, nil } func main() { fmt. [Read More]