@@ -6,32 +6,42 @@ import (
66 "unsafe"
77)
88
9- func GetPointerOfValueType (str any ) any {
10- ptr := reflect .New (reflect .ValueOf (str ).Type ())
11- ptr .Elem ().Set (reflect .ValueOf (str ))
9+ // GetPointerOfValueType returns a pointer to a new value of the same type as the input value `val`.
10+ // The new value is initialized to the input value.
11+ func GetPointerOfValueType (val any ) any {
12+ ptr := reflect .New (reflect .ValueOf (val ).Type ())
13+ ptr .Elem ().Set (reflect .ValueOf (val ))
1214 return ptr .Interface ()
1315}
1416
17+ // GetUnderlyingPointerValue dereferences the input pointer `ptr` and returns the value it points to.
1518func GetUnderlyingPointerValue (ptr any ) any {
1619 return reflect .ValueOf (ptr ).Elem ().Interface ()
1720}
1821
22+ // GetSliceType returns the element type of the input slice `slice`.
1923func GetSliceType (slice any ) reflect.Type {
2024 return reflect .TypeOf (slice ).Elem ()
2125}
2226
23- // Convert extends the reflect.Convert function an proceeds to convert subtypes
24- func Convert (value reflect.Value , t reflect.Type ) reflect.Value {
27+ // ConvertToType converts the input value `val` to the specified type `T` and returns it.
28+ func ConvertToType [T any ](val any ) T {
29+ return Convert (reflect .ValueOf (val ), reflect .TypeOf (* new (T ))).Interface ().(T )
30+ }
31+
32+ // Convert converts the input reflect.Value `val` to the specified reflect.Type `typ` and returns the result.
33+ // Convert extends the functionality of the reflect.Convert function by also convert subtypes.
34+ func Convert (val reflect.Value , typ reflect.Type ) reflect.Value {
2535 defer func () {
2636 if r := recover (); r != nil {
27- panic (fmt .Sprintf ("dreflect.Convert: value of type %s cannot be converted to type %s " , value .Type (), t ))
37+ panic (fmt .Sprintf ("dreflect.Convert: value of type %v cannot be converted to type %v " , val .Type (), typ ))
2838 }
2939 }()
30- dst := reflect .New (t ).Elem ()
31- if value .Type ().ConvertibleTo (t ) {
32- return value .Convert (t )
40+ dst := reflect .New (typ ).Elem ()
41+ if val .Type ().ConvertibleTo (typ ) {
42+ return val .Convert (typ )
3343 }
34- return convert (value , dst )
44+ return convert (val , dst )
3545}
3646
3747func convertibleTo (src , dst reflect.Type ) bool {
@@ -78,7 +88,8 @@ func convert(src reflect.Value, dst reflect.Value) reflect.Value {
7888 if src .IsNil () {
7989 return reflect .Zero (dst .Type ())
8090 }
81- dstSliceType := GetSliceType (dst .Interface ())
91+
92+ dstSliceType := dst .Type ().Elem ()
8293
8394 newSliceType := getSliceArrayType (src , dstSliceType )
8495 newSlice := reflect .MakeSlice (reflect .SliceOf (newSliceType ), src .Len (), src .Cap ())
0 commit comments