Go 语言中 interface{} 类型不支持索引的解决方法
在 Go 语言中,类型为 'interface{}' 的变量表示空接口,可以存储任何类型的值。由于它是一个空接口,因此它不支持索引,因为我们无法确定它存储的类型是否支持索引。
如果您需要在 'interface{}' 类型的变量中存储一个可以索引的值,您需要在将其存储到 'interface{}' 变量之前将其转换为适当的类型。例如,如果您想存储一个切片或数组,您需要将其转换为 '[]interface{}' 类型。
下面是一个示例,演示如何将切片转换为 '[]interface{}' 类型:
package main
import "fmt"
func main() {
s := []int{1, 2, 3}
var i interface{} = s
fmt.Println(i) // [1 2 3]
// 将 interface{} 类型转换为 []interface{} 类型
a, ok := i.([]interface{})
if !ok {
fmt.Println("conversion failed")
return
}
// 访问切片中的元素
fmt.Println(a[0]) // 1
fmt.Println(a[1]) // 2
fmt.Println(a[2]) // 3
}
在上面的示例中,我们将一个整数切片存储到 'interface{}' 变量中,并将其转换为 '[]interface{}' 类型以访问其中的元素。请注意,转换可能会失败,因此我们需要检查 'ok' 变量以确保转换成功。
原文地址: https://www.cveoy.top/t/topic/lDZ0 著作权归作者所有。请勿转载和采集!