Skip to content

Instantly share code, notes, and snippets.

@Mistobaan
Created May 9, 2013 18:22
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 Mistobaan/5549426 to your computer and use it in GitHub Desktop.
Save Mistobaan/5549426 to your computer and use it in GitHub Desktop.
Example of a Reflected function in Go 1.1
package main
import (
"bufio"
"bytes"
"fmt"
"io"
"reflect"
"runtime"
"strings"
)
func say(writer func(string) (int, error), r io.Reader) error {
s := bufio.NewScanner(r)
s.Split(bufio.ScanWords)
for n := 0; ; n++ {
if !s.Scan() {
writer(fmt.Sprintf("you said %d words.", n))
return s.Err()
}
if _, err := writer(s.Text() + ", "); err != nil {
return err
}
}
// No return statement!
}
func main() {
var buf bytes.Buffer
defer fmt.Println(&buf)
writeString := buf.WriteString
say(writeString, strings.NewReader("why hello there "+runtime.Version()))
var fn func(a, b string) int
fv := reflect.ValueOf(&fn).Elem()
fv.Set(reflect.MakeFunc(fv.Type(), func(in []reflect.Value) []reflect.Value {
n := 0
for _, v := range in {
writeString(v.String())
n++
}
return []reflect.Value{reflect.ValueOf(n)}
}))
n := fn(" and used ", "reflect.MakeFunc!")
writeString(fmt.Sprintf(" (through which you printed %v strings ;-)", n))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment