Created
October 10, 2018 18:28
-
-
Save dimroc/0d6449abb751eb4e45da0c42f70a5c8c to your computer and use it in GitHub Desktop.
Experiments with golang reflection. Create an empty slice of the type passed in in a callback: https://play.golang.org/p/Zc9HiABuMi_a
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" | |
) | |
func main() { | |
callback := func(int) bool { return false } | |
ref := reflect.ValueOf(callback) | |
fmt.Println("callback", ref.Type()) | |
requested := ref.Type().In(0) | |
fmt.Println("first parameter type", requested) | |
v := reflect.Zero(requested) | |
fmt.Println("zero value:", v) | |
slice := reflect.Zero(reflect.SliceOf(requested)).Interface() | |
fmt.Println(slice) | |
} | |
// output | |
// callback func(int) bool | |
// first parameter type int | |
// zero value: 0 | |
// [] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment