| 467 | } |
| 468 | |
| 469 | func ExampleConstExpr() { |
| 470 | code := `[fib(5), fib(3+3), fib(dyn)]` |
| 471 | |
| 472 | env := map[string]any{ |
| 473 | "fib": fib, |
| 474 | "dyn": 0, |
| 475 | } |
| 476 | |
| 477 | options := []expr.Option{ |
| 478 | expr.Env(env), |
| 479 | expr.ConstExpr("fib"), // Mark fib func as constant expression. |
| 480 | } |
| 481 | |
| 482 | program, err := expr.Compile(code, options...) |
| 483 | if err != nil { |
| 484 | fmt.Printf("%v", err) |
| 485 | return |
| 486 | } |
| 487 | |
| 488 | // Only fib(5) and fib(6) calculated on Compile, fib(dyn) can be called at runtime. |
| 489 | env["dyn"] = 7 |
| 490 | |
| 491 | output, err := expr.Run(program, env) |
| 492 | if err != nil { |
| 493 | fmt.Printf("%v", err) |
| 494 | return |
| 495 | } |
| 496 | |
| 497 | fmt.Printf("%v\n", output) |
| 498 | |
| 499 | // Output: [5 8 13] |
| 500 | } |
| 501 | |
| 502 | func ExampleAllowUndefinedVariables() { |
| 503 | code := `name == nil ? "Hello, world!" : sprintf("Hello, %v!", name)` |