【问题标题】:Convert interface to float32 in go在go中将接口转换为float32
【发布时间】:2021-07-30 14:41:38
【问题描述】:

使用类型断言无法将 interface{} 转换为 float32

package main

import (
    "fmt"
)

func main() {
    var i interface{}
    i = 1.1
    num, ok := i.(float32)
    fmt.Println(ok)
    fmt.Println(num)
}

https://play.golang.org/p/iEJWLbBCHs8

这会打印 false 和 0。如何将 interface{} 转换为 float32?

【问题讨论】:

  • i = float32(1.1)。否则编译器怎么知道你想要float32?文字 1.1 没有类型。
  • @mgagnon interface{} 值来自用户输入,所以如果它是 1.1 或其他东西,请事先确认。我尝试 num := float32(i) 有这个错误:cannot convert i (type interface {}) to type float32: need type assertion
  • 你可以这样做。 play.golang.org/p/OPiXEAWvEVl 。但是你绝对需要一个 float32 吗?正如 cd1 在其回答中所说,float64 是 go 中的默认浮点类型,因此断言 float64 将在您的最小示例中起作用。

标签: go types floating-point


【解决方案1】:

回答你的问题:

如何将 interface{} 转换为 float32?

一点也不。

您所能做的就是将 float32 存储在 interface{} 中,然后再次将其类型断言。您的代码的问题是您没有存储 float32。

【讨论】:

    【解决方案2】:

    代码运行时:

    i = 1.1
    

    它为变量i分配一个float64值;这是 Go 中十进制数字文字的默认类型。当您尝试将其转换为 float32 时,它会失败,因为这不是 i 的基础类型。

    如果要将i 转换为float32,则需要在其中输入float32 值:

    i = float32(1.1)
    

    并且转换将成功。如果您希望能够转换为float32float64,则可以尝试转换为这两种类型,如果转换为float64成功,则将结果转换为float32

    【讨论】:

      猜你喜欢
      • 2011-12-25
      • 2013-02-21
      • 2013-02-04
      • 2020-09-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-27
      • 1970-01-01
      相关资源
      最近更新 更多