Last active
December 31, 2015 16:26
-
-
Save kaneshin/a1c4c30c71844ff3b818 to your computer and use it in GitHub Desktop.
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" | |
) | |
const ( | |
Male = iota + 1 | |
Female | |
Unknown | |
) | |
type ( | |
User struct { | |
Name string | |
Gender int | |
Age int | |
} | |
) | |
func MakeSlice(v interface{}) reflect.Value { | |
typ := reflect.TypeOf(v) | |
sli := reflect.SliceOf(typ) | |
slice := reflect.MakeSlice(sli, 0, 0) | |
x := reflect.New(slice.Type()) | |
x.Elem().Set(slice) | |
return x.Elem() | |
} | |
func main() { | |
var x reflect.Value | |
apply := func(x reflect.Value) { | |
var v interface{} | |
switch x.Interface().(type) { | |
case []User: | |
v = []User{ | |
{"kaneshin", Male, 27}, | |
} | |
case []*User: | |
v = []*User{ | |
{"gopher", Unknown, 6}, | |
} | |
} | |
x.Set(reflect.ValueOf(v)) | |
} | |
output := func(x reflect.Value) { | |
fmt.Printf("Type is %+T\n", x.Interface()) | |
for i := 0; i < x.Len(); i++ { | |
fmt.Printf("- %+v\n", x.Index(i).Interface()) | |
} | |
fmt.Println() | |
} | |
// Make []User | |
x = MakeSlice(User{}) | |
apply(x) | |
output(x) | |
// Make []*User | |
x = MakeSlice(new(User)) | |
apply(x) | |
output(x) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment