为了账号安全,请及时绑定邮箱和手机立即绑定

使用兼容接口进行恐慌接口转换

使用兼容接口进行恐慌接口转换

Go
ITMISS 2022-10-04 15:58:45
我几个小时都面临着一个无法支持的问题,我必须从以太坊智能合约调用中解码数据(但这不是主题,因为这部分工作),但我将这些数据恢复到.interface{}当我想把这个空接口转换为我可以使用的结构时,我收到了以下消息:panic: interface conversion: interface {} is struct { SrcToken common.Address "json:\"srcToken\""; DstToken common.Address "json:\"dstToken\""; SrcReceiver common.Address "json:\"srcReceiver\""; DstReceiver common.Address "json:\"dstReceiver\""; Amount *big.Int "json:\"amount\""; MinReturnAmount *big.Int "json:\"minReturnAmount\""; Flags *big.Int "json:\"flags\""; Permit []uint8 "json:\"permit\"" }, not oneinch.OneInchSwapDataDesc结构是:type OneInchSwapDataDesc struct {    SrcToken        common.Address    DstToken        common.Address    SrcReceiver     common.Address    DstReceiver     common.Address    Amount          *big.Int    MinReturnAmount *big.Int    Flags           *big.Int    Permit          []uint8}当我查找类型和我得到的数据值时:fmt.Println("Type: ", reflect.TypeOf(data))fmt.Printf("Data: %+v\n", data)// Logs:// Type:  struct { SrcToken common.Address "json:\"srcToken\""; DstToken common.Address "json:\"dstToken\""; SrcReceiver common.Address "json:\"srcReceiver\""; DstReceiver common.Address "json:\"dstReceiver\""; Amount *big.Int "json:\"amount\""; MinReturnAmount *big.Int "json:\"minReturnAmount\""; Flags *big.Int "json:\"flags\""; Permit []uint8 "json:\"permit\"" }// Data: {SrcToken:0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174 DstToken:0xc2132D05D31c914a87C6611C10748AEb04B58e8F SrcReceiver:0x11431a89893025D2a48dCA4EddC396f8C8117187 DstReceiver:0x2C2d6E5E16FE924cE31784cdAd27C01D1BC62873 Amount:+10000000 MinReturnAmount:+9949450 Flags:+4 Permit:[]}我认为这个问题来自那些来自TypeOf的“json”,但我没有找到任何技巧来清除它(事实上,我真的不确定问题是否真的来自那个)。如果有人有想法,你会拯救我的大脑免于在地狱中燃烧。谢谢。
查看完整描述

1 回答

?
慕斯王

TA贡献1864条经验 获得超2个赞

接口的值类型为 。它是一种未命名的类型。仅当类型相同,或者断言的类型是接口并且基础接口类型实现该接口时,类型断言才有效。您尝试转换为的类型不是接口,而是结构。所以你可以这样做:struct { SrcToken ...}


value:=data.(struct { 

SrcToken common.Address `json:"srcToken"`

 DstToken common.Address `json:"dstToken"`

 SrcReceiver common.Address `json:"srcReceiver"`

 DstReceiver common.Address `json:"dstReceiver"`

 Amount *big.Int `json:"amount"`

 MinReturnAmount *big.Int `json:"minReturnAmount"`

 Flags *big.Int `json:"flags"`

 Permit []uint8 `json:"permit"` })

一旦你有了这个,你可以使用转换为你想要的类型:value


targetValue:=oneinch.OneInchSwapDataDesc(value)


查看完整回答
反对 回复 2022-10-04
  • 1 回答
  • 0 关注
  • 133 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号