2017-02-25 17:49
浏览 298


I'm developing a Telegram Bot API wrapper for Golang (I know there are already some but I'm doing this for learning). I have a Response struct:

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

I can't know the actual type of Result: a lot can be returned by Telegram servers; I made a struct for each one, but I don't know which one will be in Result. When Unmarshaling a JSON from an HTTP response into the Response struct, everything is loaded correctly, except Result.

In a function where I am sure Result will be an User (for example), I'm doing user := resp.Result.(*User), but I get the following error at runtime: panic: interface conversion: interface {} is map[string]interface {}, not *tgbot.User. So, Result is a map[string]interface{}. How can I transform it into a *User?

Thanks for any answers.

图片转代码服务由CSDN问答提供 功能建议

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

  type Response结构{
 Ok bool`json:“ ok”`
 ErrorCode int64`json:“ error_code”`
描述字符串 `json:“ description”`
结果界面{}`json:“ result”`

我不知道< 代码>结果:电报服务器可以返回很多结果; 我为每个结构制作了一个结构,但我不知道在 Result 中将使用哪个结构。 当 Unmarshal 将HTTP响应中的JSON放入时, Response 结构,除 Result 之外,所有内容均已正确加载。

在我确定Result将为 User (例如),我正在执行 user:= resp.Result。(* User),但是在运行时出现以下错误 panic:接口转换:interface {}是map [string] interface {},而不是* tgbot.User 。 因此, Result 是一个 map [string] interface {} 。 如何将其转换为 * User


  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • douchao0358 2017-02-25 18:02

    Make it a json.RawMessage and unmarshal it in a second step, when you're sure what type it is.

    Take a look at the examples at

    解决 无用
    打赏 举报

相关推荐 更多相似问题