小编lov*_*o-h的帖子

在 Go 中,如何将 bson byte[] 数据解组为结构数组?

当结构数组传递给参数时,将Unmarshal 字节 []数据转换为结构数组的最佳方法是interface{}什么?

出于演示目的,在以下代码中,我使用bson.Marshal()oninStructArr来获取byte[]数据类型。这样我就可以用bson.Unmarshal(...)管道进入outStructArr.

import "gopkg.in/mgo.v2/bson"

type User struct {
    Name string
}

func DecodeArrData(inStructArr, outStructArr interface{}) {
    inStructArrData, _ := bson.Marshal(inStructArr)
    bson.Unmarshal(inStructArrData, outStructArr) // <-- Error happens here
    // What's the right way of accomplishing this?
}

func Main() {
    outUsers := &[]User{}
    inUsers := []User{User{"A"}, User{"B"}}

    DecodeArrData(inUsers, outUsers)
}
Run Code Online (Sandbox Code Playgroud)

当我这样做时,我得到的错误消息是:Unsupported document type for unmarshalling: []User. 这样做的正确方法是什么?

提前致谢!

database struct go bson

2
推荐指数
1
解决办法
2679
查看次数

标签 统计

bson ×1

database ×1

go ×1

struct ×1