Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle returning two objects within switch case statement

Tags:

go

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
}
like image 340
NuLLByt3 Avatar asked Jan 17 '26 19:01

NuLLByt3


2 Answers

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

like image 83
Zak Avatar answered Jan 19 '26 20:01

Zak


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
}
like image 39
Himanshu Avatar answered Jan 19 '26 19:01

Himanshu