douhuan7862 2014-07-16 09:49
浏览 35
已采纳

创建未知类型的切片?

I'm trying to fetch multiple values using this function (from go-couchbase).

func (b *Bucket) Gets(k string, rv interface{}, caso *uint64) error {
    data, _, cas, err := b.GetsRaw(k)
    if err != nil {
        return err
    }
    if caso != nil {
        *caso = cas
    }
    return json.Unmarshal(data, rv)
}

The problem is that I don't know how to create a slice of rv, since I don't know its type in my function, and I have no idea how big it will be so I can't really access the rv slice through indexes, right?

I want to be as general as possible, so creating a function per rv struct isn't really optimal and the GetBulk function only returns a []byte.

Is it even possible to do what I want in go?

  • 写回答

2条回答 默认 最新

  • douxunchen3498 2014-07-16 14:32
    关注

    You can inspect the type information using the reflect package. If we have a function that has an argument rv interface{} where we expect a pointer to a slice to be passed in, we can create a reflect.Value that refers to that slice:

    slice := reflect.ValueOf(rv).Elem()
    

    We can reinitialise the slice as follows:

    slice.Set(reflect.MakeSlice(slice.Type(), length, capacity))
    

    We can determine the element type of this slice with:

    elemType := slice.Type().Elem()
    

    And then create another reflect.Value that represents a pointer to a newly allocated instance of that type:

    v := reflect.New(elemType)
    

    Now v.Interface() would be appropriate to pass to a function like json.Unmarshal. Once it has been filled, it can be appended to the slice:

    slice.Set(reflect.Append(slice, v.Elem()))
    

    For a full example that decodes a slice of JSON documents into an arbitrary slice type, see http://play.golang.org/p/G-SHQO2MAT

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 根据以下文字信息,做EA模型图
  • ¥15 删除虚拟显示器驱动 删除所有 Xorg 配置文件 删除显示器缓存文件 重启系统 可是依旧无法退出虚拟显示器
  • ¥15 vscode程序一直报同样的错,如何解决?
  • ¥15 关于使用unity中遇到的问题
  • ¥15 开放世界如何写线性关卡的用例(类似原神)
  • ¥15 关于并联谐振电磁感应加热
  • ¥60 请查询全国几个煤炭大省近十年的煤炭铁路及公路的货物周转量
  • ¥15 请帮我看看我这道c语言题到底漏了哪种情况吧!
  • ¥60 关机时蓝屏并显示KMODE_EXCEPTION_NOT_HANDLED,怎么修?
  • ¥66 如何制作支付宝扫码跳转到发红包界面