错误“cannot convert data (type interface{}) to type string”:Go 中的 type assertion
大家好!我是 Go 的新手,遇到了一个两天都解决不了的问题。我有一个函数,它从外部 API 接收类型为 `interface{}` 的数据。我尝试将其转换为字符串,但编译器报错:“cannot convert data (type interface{}) to type string: need type assertion”。
这是我的代码:
```go
package main
import "fmt"
func processData(data interface{}) string {
// 尝试将 interface{} 转换为字符串
result := string(data)
return result
}
func main() {
var val interface{} = "Hello, World!"
result := processData(val)
fmt.Println(result)
}
```
我知道 `interface{}` 可以存储任何值,但通过 `string(data)` 进行类型转换难道不应该有效吗?在其他语言中,比如 Python 或 Java,这种转换是没问题的。我已经尝试过使用 `data.(string)`,但同样报错。我哪里做错了?如何正确地从 `interface{}` 中提取字符串?