Identify the bug in the following Go function. It should handle different types and return an error if the type is not supported.

Go & Rust interview question for Advanced practice.

Answer

The function is missing a final return statement or a default case, so it will fail to compile.

Explanation

The function is declared to return a (string, error), which means every possible execution path must end with a return statement. If the switch receives a type that is not int, string, or float64, it will complete without hitting a return. The Go compiler will detect this and report a 'missing return at end of function' error. The fix is to add a default case to the switch that returns an error.

Related Questions