Go中的错误“无法将数据(类型interface{})转换为类型string:需要类型断言”
大家好!我刚开始学习 Go 语言,遇到了一个让我困惑的错误。我写了一个简单的程序,从 JSON 中获取数据并尝试使用它们。
以下是我的代码:
```go
package main
import (
"encoding/json"
"fmt"
)
func main() {
jsonString := `{"name": "John", "age": 30}`
var data interface{}
json.Unmarshal([]byte(jsonString), &data)
name := data["name"] // 错误:cannot convert data (type interface {}) to type string: need type assertion
fmt.Println(name)
}
```
我期望 `data["name"]` 能返回字符串 "John",但编译器报错:"cannot convert data (type interface {}) to type string: need type assertion"。我明白 `data` 的类型是 `interface{}`,但我该如何获取字符串的值呢?我试过写 `data.(map[string]interface{})["name"]`,但还是不行。请解释一下我哪里做错了,以及如何在 Go 中正确地从接口中提取值。提前感谢!