Go provides two ways to handle errors, but I'm not sure which one to use.
Assuming I'm implementing a classic ForEach function that takes a slice or map as an argument. To check if the iterability went through, I could do:
func ForEach(iterable interface{}, f interface{}) { if isNotIterable(iterable) { panic("Should pass in a slice or map!") } }
or
func ForEach(iterable interface{}, f interface{}) error { if isNotIterable(iterable) { return fmt.Errorf("Should pass in a slice or map!") } }
I saw some discussions that said panic() should be avoided, but people also say that if a program cannot recover from an error, you should panic() .
Which should i use? And what is the main principle for choosing the right one?
source share