2015-08-19 13:02
浏览 41


I am trying to build a library that can read multiple different types of objects out of JSON files (the actual library pulls them out of couchdb, but for the purposes of this it's loading them from json).

My library doesn't know anything about the concrete type of object being loaded, hence the "CreateObject()" call below (which is satisfied by an interface in the real code).

I'm having a problem that when I try to cast the object created by the CreateObject() call back to my concrete type (MyType in the example) I'm getting a panic:

panic: interface conversion: interface is map[string]interface {}, not main.MyType

I'd like to know where I'm going wrong here, or whether there's another more go-like way I should be approaching this problem. If I was doing it in Java I'd be using generics and would expect it to be straightforward.

Note that if I comment out the json.NewDecoder... line then the code works (prints out a blank line, as expected). This implies something is happening in the Decode operation.

Runnable example follows:

package main

import (

type MyType struct {
    Name string `json:"name"`
    Age  int32  `json:"age"`

func CreateObject() interface{} {
    return MyType{}

func LoadJsonData() interface{} {
    obj := CreateObject()
    jsonStr := `{"name":"Person", "age":30}`

    return obj

func main() {

    obj := LoadJsonData()

    // This works for some reason
    // y := obj.(map[string]interface{})
    // fmt.Println(y["name"])

    // This causes a panic
    x := obj.(MyType)


  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • duanli9591 2015-08-19 13:18

    You should use pointer instead of struct:

    func CreateObject() interface{} {
        return &MyType{} // here
    // This causes a panic
    x := obj.(*MyType) // and there


    If you want to read more about it, consider the following thread: golang fails to parse json for reflection created object

    打赏 评论

相关推荐 更多相似问题