使用接口获取结构体的值 [英] Get value of struct with interfaces

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

问题描述

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

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

type orderBook struct {出价 [][] 接口{} `json:"出价"`Asks [][]interface{} `json:"Asks"`}

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

url := "https://www.binance.com/api/v1/depth?symbol=MDABTC&limit=500"响应,错误:= http.Get(url)如果错误!= nil {恐慌(错误)}延迟 resp.Body.Close()身体,错误:= ioutil.ReadAll(resp.Body)如果错误!= nil {恐慌(错误)}别的{书 := orderBook{}如果错误 := json.Unmarshal(body, &book);错误!= 零{恐慌(错误)}

但是每当我尝试使用结构进行操作时,例如:

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

我收到一个错误:

<块引用>

无效操作:book.Asks[i][0] * book.Asks[i][1] (operator * not在接口上定义)

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

对不起,如果这看起来很基础,我刚开始学习围棋.

解决方案

在 Golang Spec

<块引用>

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

x.(T)

<块引用>

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

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

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

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

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

Go Playground

上的结帐代码

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]

I get an error:

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

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

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

解决方案

In Golang Spec

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

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.

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

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

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)

Checkout code on Go playground

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

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