登录
首页 >  Golang >  Go问答

Golang中如何处理动态接口类型?

来源:stackoverflow

时间:2024-03-29 18:51:35 126浏览 收藏

大家好,我们又见面了啊~本文《Golang中如何处理动态接口类型?》的内容中将会涉及到等等。如果你正在学习Golang相关知识,欢迎关注我,以后会给大家带来更多Golang相关文章,希望我们能一起进步!下面就开始本文的正式内容~

问题内容

我正在尝试处理动态接口类型,但我不知道接口的类型是 float64 还是 int64。我正在使用 api 并解码地图上的响应,其中价格有时是整数,有时是浮点数。例如json 响应有时是 {price: 35},有时是 {price: 35}

我在这里创建了一个示例代码

package main
import "fmt"

func main() {

    response := make(map[string]interface{})
    response["price"] = 2.1

    response1 := make(map[string]interface{})
    response1["price"] = 2

    price_response, _ := response["price"].(float64)
    price_response1, _ := response1["price"].(float64)

    fmt.println(price_response, "==> price_response") //output = 2.1
    fmt.println(price_response1,"==> price_response1") // //output = 0
}

输出是 get is

2.1 price_response
0 price_response1

现在,我必须在对接口类型进行类型断言时静态定义类型。我应该如何处理这种类型问题以避免得到 0 而是将实际值转换为 float64?


解决方案


我应该如何处理这种类型问题以避免得到 0 而是将实际值转换为 float64?

t, ok := i.(t)

这行代码检查接口值 i 是否包含具体类型 t。如果没有,ok 将为 false,t 将是类型 t 的零值

price_response1, _ := response1["price"].(float64)

这里的response1["price"]不包含float64类型。因此,price_response1 的 float64 类型值为零,即 0。

要将接口{}的底层类型打印为字符串,您可以使用:

gettype := fmt.sprintf("%t", response1["price"])
fmt.println(gettype)

如果基础类型是 int,请参阅下面的代码以获取转换为 float64 的实际值:

package main

import "fmt"

func converttofloat64(resp interface{}) {
    switch v := resp.(type) {
    case int:
        fmt.println(float64(v), "==> price_response1")

    case float64:
        fmt.println(v, "==> price_response")
    default:
        fmt.println("unknown")
    }
}

func main() {
    response := make(map[string]interface{})
    response["price"] = 2.1
    converttofloat64(response["price"])
    response1 := make(map[string]interface{})
    response1["price"] = 2
    converttofloat64(response1["price"])

}

输出:

2.1 ==> price_response
2 ==> price_response1

理论要掌握,实操不能落!以上关于《Golang中如何处理动态接口类型?》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>