I’m looking for some links to explain(hopefully in simplistic terms) GoLang’s type system.
I can use GoLang’s type system but I find that I’m guessing at what is possible with GoLang’s type system when I start venturing off the beaten path.
Example: I tried solving a problem(below) that creates lazy fibonacci generator.
Basic fibonacci function(fib)
func fib(n uint) uint {
if n == 0 {
return 0
} else if n == 1 {
return 1
} else {
return fib(n-1) + fib(n-2)
}
}
Create a type to help with the lazy fibonacci generator function.
type Func[T any] func() (T, Func[T])//doesn't need to be generic but what the heck!
The generator function which returns the calculated fibonacci element and a function which returns the next fibonacci element and the generator function for the (next + 1)…etc
func cal_fib_elem_and_next(n uint) (uint, Func[uint]) {
return fib(n), Func[uint](func() (uint, Func[uint]) { return cal_fib_elem_and_next(n + 1) })
}
Usage.
func main() {
n, next_func := cal_fib_elem_and_next(20)
fmt.Printf("elem: %d, %T\n", n, next_func)
n, next_func = next_func()
fmt.Printf("elem: %d, %T\n", n, next_func)
n, next_func = next_func()
fmt.Printf("elem: %d, %T\n", n, next_func)
n, next_func = next_func()
fmt.Printf("elem: %d, %T\n", n, next_func)
}
Output:
I arrived at this solution by just trying(guessing) it… I didn’t know(before hand) if GoLang’s type system would handle this.
I find that GoLang’s type system is well documented when you are on the beaten path but as soon as you are off that beaten path… You are on your own.