通过接口获取结构的价值 [英] Get value of struct with interfaces

查看:70
本文介绍了通过接口获取结构的价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试解析此请愿书( https: //www.binance.com/api/v1/depth?symbol=MDABTC&limit=500 )

I'm trying to parse this petition (https://www.binance.com/api/v1/depth?symbol=MDABTC&limit=500)

我在为它创建结构时遇到了很多问题,所以我使用了自动化工具,这就是我的结构的样子:

I was having tons of problems to create an struct for it, so I used an automated tool, this is what my struct looks like:

type orderBook struct {
    Bids         [][]interface{} `json:"Bids"`
    Asks         [][]interface{} `json:"Asks"`
}

我通过执行以下操作来恢复并解析请愿书:

I recover and parse the petition by doing:

url := "https://www.binance.com/api/v1/depth?symbol=MDABTC&limit=500"
resp, err := http.Get(url)
if err != nil {
    panic(err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
    panic(err)
}else{
    book := orderBook{}
if err := json.Unmarshal(body, &book); err != nil {
    panic(err)
}

但是每当我尝试对该结构进行操作时,就像:

But whenever I try to make an operation with the struct, like:

 v := book.Asks[i][0] * book.Asks[i][1]

我得到一个错误:

无效操作:book.Asks [i] [0] * book.Asks [i] [1](运算符*不 在接口上定义)

invalid operation: book.Asks[i][0] * book.Asks[i][1] (operator * not defined on interface)

我如何定义它?我是否需要为bids/asks创建一个结构,如果是的话,那会是什么样?

How do I define it? Do I need to create an struct for bids/asks, if so, how would that look like?

对不起,如果这看起来很简单,我就开始学习go.

Sorry if this seems basic, I just started learning go.

推荐答案

在Golang中规范

对于接口类型为T且类型为T的表达式x,主要 表达

For an expression x of interface type and a type T, the primary expression

x.(T)

断言x不是nil,并且存储在x中的值是T类型. x.(T)称为类型断言.

asserts that x is not nil and that the value stored in x is of type T. The notation x.(T) is called a type assertion.

要获取字符串类型的基础值,您需要从接口键入assert到字符串.

Fetching an underlying value of string type you need to type assert to string from interface.

books.Asks[0][0].(string)

要对其执行算术运算,您需要将字符串转换为float64以考虑十进制值

For performing an arithmetic operation on same you needs to convert string into float64 to take into account decimal values

v := strconv.ParseFloat(books.Asks[0][0].(string), 64) * strconv.ParseFloat(books.Asks[0][1].(string), 64)

游乐场

这篇关于通过接口获取结构的价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆