()
| 500 | } |
| 501 | |
| 502 | func ExampleAllowUndefinedVariables() { |
| 503 | code := `name == nil ? "Hello, world!" : sprintf("Hello, %v!", name)` |
| 504 | |
| 505 | env := map[string]any{ |
| 506 | "sprintf": fmt.Sprintf, |
| 507 | } |
| 508 | |
| 509 | options := []expr.Option{ |
| 510 | expr.Env(env), |
| 511 | expr.AllowUndefinedVariables(), // Allow to use undefined variables. |
| 512 | } |
| 513 | |
| 514 | program, err := expr.Compile(code, options...) |
| 515 | if err != nil { |
| 516 | fmt.Printf("%v", err) |
| 517 | return |
| 518 | } |
| 519 | |
| 520 | output, err := expr.Run(program, env) |
| 521 | if err != nil { |
| 522 | fmt.Printf("%v", err) |
| 523 | return |
| 524 | } |
| 525 | fmt.Printf("%v\n", output) |
| 526 | |
| 527 | env["name"] = "you" // Define variables later on. |
| 528 | |
| 529 | output, err = expr.Run(program, env) |
| 530 | if err != nil { |
| 531 | fmt.Printf("%v", err) |
| 532 | return |
| 533 | } |
| 534 | fmt.Printf("%v\n", output) |
| 535 | |
| 536 | // Output: Hello, world! |
| 537 | // Hello, you! |
| 538 | } |
| 539 | |
| 540 | func ExampleAllowUndefinedVariables_zero_value() { |
| 541 | code := `name == "" ? foo + bar : foo + name` |
nothing calls this directly
no test coverage detected
searching dependent graphs…