go - 如何将接口(interface)数组转换为 float

标签 go type-conversion

bound :=  []interface{}{1.00, 1.00, 1.00, 1.00}
new_bound := bound.([]float32)
log.Println(new_bound)

如何将接口(interface)数组转换为 float 组?

invalid type assertion: bound.([]float32) (non-interface type []interface {} on left)

在实际项目中

panic: interface conversion: interface is []interface {}, not []float32

最佳答案

在您的示例中,您有一个 slice ,其中它包含的每个项目都是一个interface{},而不是说,一个表示 [] 的单个 interface{} float32,因此你不能像那样简单地转换整个集合。相反,您必须迭代它并对集合中的每个项目进行类型断言。这是一个例子; https://play.golang.org/p/dD4161xgaV

bound :=  []interface{}{1.00, 1.00, 1.00, 1.00}
new_bound := []float64{}
for _, v := range bound {
     new_bound = append(new_bound, v.(float64))
}

还有一件事需要注意,这些字面量隐含了它们的类型,它是 float64,因此您实际上需要它。

编辑:包括这个由 OneOfOne 发布的更优化的解决方案;

func main() {
    bound := []interface{}{1.00, 1.10, 1.11, 1.111}
    new_bound := make([]float64, len(bound))
    for i := range bound {
        new_bound[i] = bound[i].(float64)
    }
    fmt.Println(new_bound)

}

关于go - 如何将接口(interface)数组转换为 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37079018/

相关文章:

json - 结构标签选项不为字段提供标签名称

testing - 在测试中找不到 init 函数中使用的相对路径

string - 在 GoLang 中打印“(双引号)

c++ - 转换为索引和指针并引用容器的类

arrays - 如何将数组发送到函数

python - 将 24 位整数转换为 32 位整数的更多 Pythonic 方式

c++ - 使用 boost::chrono 计算执行时间

Python 字符串到列表的转换

Java 相当于 C# Array.Copy

mongodb - 如何在 Go 中使用 $indexOfArray?