如何从使用interface {}输入的golang map [string]字符串中提取值?
问题描述:
This question already has an answer here:
- Explain Type Assertions in Go 3 answers
- Accessing Nested Map of Type map[string]interface{} in Golang 1 answer
- Typed, nested map of map[string]interface{} returns “type interface {} does not support indexing” 1 answer
- get value form nested map type map[string]interface{} 2 answers
- how to access nested Json key values in Golang 3 answers
I have something like this:
x1 := someFunctionWithAnInterfaceReturnValue()
and the underlying type is something like this:
x2 := map[string] string{"hello": "world"}
How would I access value in x1?
Essentially I want the equivalent of this for x1:
var value string = x2["hello"]
</div>
答
Use a type assertion:
x1 := someFunctionWithAnInterfaceReturnValue()
x2, ok := x1.(map[string]string)
if !ok {
// handle unexpected type
}
var value string = x2["hello"]