| 1 | package interp_test |
| 2 | |
| 3 | import ( |
| 4 | "fmt" |
| 5 | "log" |
| 6 | |
| 7 | "github.com/traefik/yaegi/interp" |
| 8 | ) |
| 9 | |
| 10 | // Generic example. |
| 11 | func Example_eval() { |
| 12 | // Create a new interpreter context |
| 13 | i := interp.New(interp.Options{}) |
| 14 | |
| 15 | // Run some code: define a new function |
| 16 | _, err := i.Eval("func f(i int) int { return 2 * i }") |
| 17 | if err != nil { |
| 18 | log.Fatal(err) |
| 19 | } |
| 20 | |
| 21 | // Access the interpreted f function with Eval |
| 22 | v, err := i.Eval("f") |
| 23 | if err != nil { |
| 24 | log.Fatal(err) |
| 25 | } |
| 26 | |
| 27 | // Returned v is a reflect.Value, so we can use its interface |
| 28 | f, ok := v.Interface().(func(int) int) |
| 29 | if !ok { |
| 30 | log.Fatal("type assertion failed") |
| 31 | } |
| 32 | |
| 33 | // Use interpreted f as it was pre-compiled |
| 34 | fmt.Println(f(2)) |
| 35 | |
| 36 | // Output: |
| 37 | // 4 |
| 38 | } |