go - 在类型切换中使用 strconv.FormatFloat() 时遇到问题

标签 go

我只是想使用类型开关来处理时间、float32 和 float64。它适用于时间和 float64s,但 strconv.FormatFloat(val, 'f', -1, 32) 一直告诉我不能使用 type float32 作为类型 float64。我不明白这是怎么回事,所以我一定是遗漏了什么或者误解了我应该如何为 float32s 调用 FormatFloat()

func main() {
    fmt.Println(test(rand.Float32()))
    fmt.Println(test(rand.Float64()))
}

func test(val interface{}) string {
    switch val := val.(type) {
        case time.Time:
            return fmt.Sprintf("%s", val)
        case float64:
            return strconv.FormatFloat(val, 'f', -1, 64)
        case float32:
            return strconv.FormatFloat(val, 'f', -1, 32) //here's the error
        default:
            return "Type not supported!"
    }
}

错误:

cannot use val (type float32) as type float64 in argument to strconv.FormatFloat

最佳答案

FormatFloat 的第一个参数需要是 float64,而您传递的是 float32。解决此问题的最简单方法是简单地将 32 位 float 转换为 64 位 float 。

case float32:
    return strconv.FormatFloat(float64(val), 'f', -1, 32)

http://play.golang.org/p/jBPaQ-jMBT

关于go - 在类型切换中使用 strconv.FormatFloat() 时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24748452/

相关文章:

html - Go 模板中的嵌套范围

c - Windows DLL 文件的正确构建模式是什么?

path - 结合绝对路径和相对路径得到新的绝对路径

go - 为什么从来没有到达return语句

go - 如果发生错误,请重复代码

go - 指定用于在 Go 中查找的 DNS 服务器

reflection - 在 Go 中,reflect.Interface 是哪种值?

mysql - Golang aws xray.sql错误

linux - 我如何在 Golang 程序中检测 linux 分布?

java - 不同语言版本的Murmurhash会得到不同的结果