Question: Go provides two ways of handling errors, but I'm not sure which one to use.

Assuming I'm implementing a classic `ForEach` function which accepts a slice or a map as an argument. To check whether an iterable is passed in, 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 saying `panic()` should be avoided, but people also say that if program cannot recover from error, you should `panic()`.

Which one should I use? And what's the main principle for picking the right one?

Answer: 
**Use `panic`.**

Because your use case is to **catch a bad use of your API**. This should never happen at runtime if the program is calling your API properly.

In fact, any program calling your API with correct arguments will behave in the same way *if the test is removed*. The test is there only to fail early with an error message helpful to the programmer that did the mistake. Ideally, the panic might be reached once during development when running the testsuite and the programmer would fix the call even before committing the bad code, and that incorrect use would never reach production.

See also [this reponse](https://stackoverflow.com/a/22865084/328115) to question *Is function parameter validation using errors a good pattern in Go?*.
If some mandatory requirement is not provided or not there while starting the service (eg. database connection, some service configuration which is required) then you should use panic.

There should be return error for any user response or server side error.