Create a fragment of an unknown type?

I am trying to extract 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 from 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 access the rvcut indexes, right?

I want to be as general as possible, so creating a function in a rvstruct is actually not optimal, and the GetBulk function returns a []byte.

Is it possible to do what I want?

+4
source share
2 answers

reflect. , rv interface{}, , , reflect.Value, :

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

:

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

:

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

reflect.Value, :

v := reflect.New(elemType)

v.Interface() , json.Unmarshal. , :

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

, JSON , . http://play.golang.org/p/G-SHQO2MAT

+3

go-couchbase#Bucket.Gets , [], wiki " InterfaceSlice"

var dataSlice []int = foo()
var interfaceSlice []interface{} = make([]interface{}, len(dataSlice))
for i, d := range dataSlice {
    interfaceSlice[i] = d
}

, "-", .

, " Gets", interface{} []interface.

+2

Source: https://habr.com/ru/post/1548615/


All Articles