使用类型断言将切片中的元素转换为对应类型,再进行遍历。
示例代码如下:
mixedSlice := []interface{}{"hello", 42, true}
for _, val := range mixedSlice {
switch v := val.(type) {
case string:
fmt.Println("string:", v)
case int:
fmt.Println("int:", v)
case bool:
fmt.Println("bool:", v)
}
}
运行结果:
string: hello
int: 42
bool: true
下一篇:遍历活动记录中的数组元素