at kaneshin
Home Talks Posts Links

01 Jan 2016
Make a slice from a type

go

Do you know how to make a slice from a type of value. We will do it with reflect.MakeSlice of reflect package but it’s a little complex to fulfill.

Implementation

Actually, it’s easy if you know how to implement.

type User struct {
	Name   string
	Gender int
	Age    int
}

func main() {
	// Assign user
	user := User{}

	// Assign a value of reflect.Type
	typ := reflect.TypeOf(user)

	// Assign a slice using reflect.MakeSlice
	slice := reflect.MakeSlice(reflect.SliceOf(typ), 0, 0)

	x := reflect.New(slice.Type())
	x.Elem().Set(slice)

    // []User
	var userValue reflect.Value = x.Elem()

	// Do something...
}

At first, make reflect.Type from a value which is what you want slice. Then, use reflect.MakeSlice to obtain your slice.

Code, All of your need

I wrote an example of MakeSlice for you all! So see and touch the following code. :)

Simply Run the code below.



Til next time,
kaneshin at 00:30