Skip to content

Instantly share code, notes, and snippets.

@kaneshin
Last active December 31, 2015 16:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kaneshin/a1c4c30c71844ff3b818 to your computer and use it in GitHub Desktop.
Save kaneshin/a1c4c30c71844ff3b818 to your computer and use it in GitHub Desktop.
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