我正在为Golang开发Telegram Bot API包装器(我知道已经有一些包装了,但是我正在做这个学习)。我有一个响应结构:

type Response struct {
  Ok bool `json:"ok"`
  ErrorCode int64 `json:"error_code"`
  Description string `json:"description"`
  Result interface{} `json:"result"`
}

我不知道Result的实际类型:电报服务器可以返回很多信息。我为每个构建了一个结构,但是我不知道Result中将包含哪个结构。
Unmarshal将HTTP响应中的JSON转换为Response结构时,除Result之外的所有内容均已正确加载。

在我确定Result将是User(例如)的函数中,我正在执行user := resp.Result.(*User),但是在运行时出现以下错误:panic: interface conversion: interface {} is map[string]interface {}, not *tgbot.User。因此,Resultmap[string]interface{}。如何将其转换为*User

感谢您的回答。

最佳答案

确定它是什么类型后,将其设置为json.RawMessage并在第二步中将其解码。

看一看https://golang.org/pkg/encoding/json/#RawMessage的示例。

10-07 19:08
查看更多