Created
May 9, 2013 18:22
-
-
Save Mistobaan/5549426 to your computer and use it in GitHub Desktop.
Example of a Reflected function in Go 1.1
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 ( | |
"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