Search code examples
gogo-gin

interface conversion: interface{} is nil, not bool


I'm relatively new to Go.

I'm making changes to an existing project. I need to retrieve an element's value that might be present in an HTTP request's body and pop it.

var returnValues = body.Params["returnValues"].(bool)
delete(body.Params, "returnValues")

I'm getting error at first line.

interface conversion: interface {} is nil, not bool

Sample body:

{
"Params": {
    "returnValues": true
    }
}

Solution

  • Always if you access a map of interfaces or default nil types and do things using that map, make sure that value for the key is existing in the map before use it. If that value is not exist in the map, it will return nil and panic with nil reference.

    r, ok := body.Params["returnValues"]
        if !ok {
            // returnValues not present in Params map. Handle the scenario
            // and don't continue below 
        }
        var returnValues = r.(bool)
        delete(body.Params, "returnValues")
    

    And also if you are not sure about the variable type you are accessing, then use type assertion and see whether your type is ok or not. Then if it is null, then it also return false for the type assertion.

    returnValues, ok := body.Params["returnValues"].(bool)
        if !ok {
            // returnValues may not present in Params map. or it is not an 
            // boolean type, handle scenario here
        }
        delete(body.Params, "returnValues")