how to get slice type of a type?

1,085 views
Skip to first unread message

Davies Liu

unread,
Apr 1, 2012, 4:13:26 AM4/1/12
to golang-nuts
Hi, nuts:

I try to get reflect.MakeSlice() according to the element Type, how to ?

If in reflect package, It's like this:

func MakeTypeSlice(typ Type, len, cap int) Value {
     // check typ, len and cap

    var x []byte
    s := (*reflect.SliceHeader)(unsafe.Pointer(&x))
    s.Data = uintptr(unsafe_NewArray(typ, cap))
    s.Len = len
    s.Cap = cap
    
    styp := arrayType{} // TODO
    return Value{styp, unsafe.Pointer(&x), flagIndir | flag(Slice) << flagKindShift)}
}

How can i archive this outside of reflect package ?

--
 - Davies

Rémy Oudompheng

unread,
Apr 1, 2012, 4:44:15 AM4/1/12
to Davies Liu, golang-nuts
Le 1 avril 2012 10:13, Davies Liu <davie...@gmail.com> a écrit :
> Hi, nuts:
>
> I try to get reflect.MakeSlice() according to the element Type, how to ?
>
> If in reflect package, It's like this:
>
> func MakeTypeSlice(typ Type, len, cap int) Value {
>      // check typ, len and cap
>
>     var x []byte
>     s := (*reflect.SliceHeader)(unsafe.Pointer(&x))
>     s.Data = uintptr(unsafe_NewArray(typ, cap))
>     s.Len = len
>     s.Cap = cap
>
>     styp := arrayType{} // TODO

There's some work needed to do that while perserving type safety:
* two successive calls must return Values of the same Type
* two concurrent calls must return Values of the same Type
* a call to MakeSliceOf(TypeOf(MyType)) must return a Value of the
same type as ValueOf([]MyType{}).

Issue number 2339 tracks this kind of request:
http://code.google.com/p/go/issues/detail?id=2339

Rémy.

Reply all
Reply to author
Forward
0 new messages