Skip to content

Instantly share code, notes, and snippets.

@dimroc
Created October 10, 2018 18:28
Show Gist options
  • Save dimroc/0d6449abb751eb4e45da0c42f70a5c8c to your computer and use it in GitHub Desktop.
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
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