要获取 '[]interface{}' 中的数据,需要使用类型断言。因为 'interface{}' 可以包含任何类型的值,因此需要判断其实际的类型。以下是一个示例代码:

package main

import "fmt"

func main() {
    arr := []interface{}{'hello', 123, true}

    for _, v := range arr {
        switch val := v.(type) {
        case string:
            fmt.Println('string:', val)
        case int:
            fmt.Println('int:', val)
        case bool:
            fmt.Println('bool:', val)
        }
    }
}

输出结果为:

string: hello
int: 123
bool: true

通过类型断言,我们可以判断 'interface{}' 中的实际类型,并进行相应的操作。

Golang []interface{} 数据获取与类型断言

原文地址: https://www.cveoy.top/t/topic/lHaW 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录