接口转换:interface{} 是 nil,而不是 bool。

huangapple go评论82阅读模式
英文:

interface conversion: interface{} is nil, not bool

问题

我相对于Go语言还比较新手。

我正在对一个现有项目进行更改。
我需要获取可能存在于HTTP请求体中的元素的值,并将其删除。

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

我在第一行遇到了错误。

接口转换:interface {}是nil,而不是bool

示例请求体:

{
"Params": {
    "returnValues": true
    }
}
英文:

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
    }
}

答案1

得分: 5

始终在访问接口映射或默认空类型的地图时,确保在使用之前检查该键的值是否存在于地图中。如果该值不存在于地图中,它将返回nil并出现nil引用的panic。

r, ok := body.Params["returnValues"]
if !ok {
    // Params映射中不存在returnValues。处理该场景
    // 并且不要继续下面的操作
}
var returnValues = r.(bool)
delete(body.Params, "returnValues")

而且,如果您不确定正在访问的变量类型,请使用类型断言并查看您的类型是否正确。然后,如果它为空,类型断言也会返回false。

returnValues, ok := body.Params["returnValues"].(bool)
if !ok {
    // returnValues可能不存在于Params映射中,或者它不是布尔类型,在此处处理场景
}
delete(body.Params, "returnValues")
英文:

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")

huangapple
  • 本文由 发表于 2021年9月1日 23:55:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/69017084.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定