I'm writing type assertion helper method which accepts an interface{} and returns string along with map[string]interface{}. I'm returning both objects within a case statement. Why is it asking for return at end of function? Am i missing a break?
func typeAssertionHelper(r interface{}) (string, map[string]interface{}) {
switch g := r.(type) {
case string:
return g, nil
case []interface{}:
for _, v := range g {
switch s := v.(type) {
case string:
return s, nil
case map[string]interface{}:
return "", s
}
}
}
// missing return end of function
}
The r interface{} that's being passed in does not necessarily match one of the cases that you have in the switch block.
Essentailly the switch is not exhaustive.
You could extend the switch with a default case:
switch g := r.(type) {
case string:
...
case []interface{}:
...
default:
...
}
Or just return something at the end of the function
return "", nil
Add a return with nil value at the of the function. Since you are returning from a function you should have a return at the end of function.
package main
import (
"fmt"
"runtime"
)
func Do() string{
fmt.Print("Go runs on ")
switch os := runtime.GOOS; os {
case "darwin":
return "darwin"
case "linux":
return "linux"
default:
// freebsd, openbsd,
// plan9, windows...
return fmt.Sprintf("%s.", os)
}
return "OS"
}
func main() {
value := Do()
fmt.Println(value)
}
Or what you can do is have a single return statement in the end of the function. But assign a value in every case which will be returned.
func Do() string{
fmt.Print("Go runs on ")
var value string
switch os := runtime.GOOS; os {
case "darwin":
value = "darwin"
case "linux":
value = "linux"
default:
// freebsd, openbsd,
// plan9, windows...
value = fmt.Sprintf("%s.", os)
}
return value
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With