Created
March 7, 2015 22:34
-
-
Save maksadbek/67112053212893c06ab8 to your computer and use it in GitHub Desktop.
Generate Slice using reflection
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"reflect" | |
) | |
type Model interface { | |
GetHello() | |
} | |
type Orders struct { | |
Id int64 | |
} | |
func (o Orders) GetHello() { | |
fmt.Println("Hello") | |
} | |
func resSliceOrders(inf interface{}) string { | |
switch t := inf.(type) { | |
case []Orders: | |
return "[]Orders" | |
case *[]Orders: | |
*t = append(*t, Orders{Id: 77}) | |
*t = append(*t, Orders{Id: 88}) | |
return "this is it *[]Orders" | |
default: | |
return fmt.Sprintf("%+v\n", t) | |
} | |
return "" | |
} | |
func populate(m ...Model) error { | |
var err error | |
for _, x := range m { | |
// Create a slice to begin with | |
myType := reflect.TypeOf(x) | |
slice := reflect.MakeSlice(reflect.SliceOf(myType), 0, 0) | |
// Create a pointer to a slice value and set it to the slice | |
x := reflect.New(slice.Type()) | |
x.Elem().Set(slice) | |
objSlice := x.Interface() | |
fmt.Println(resSliceOrders(objSlice)) | |
fmt.Printf("%+v\n", objSlice) | |
sl:=reflect.Indirect(reflect.ValueOf(objSlice)) | |
for i:=0; i < sl.Len(); i++ { | |
fmt.Printf("%+v\n",sl.Index(i).Interface()) | |
} | |
} | |
return err | |
} | |
func main() { | |
populate(Orders{}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment