MCPcopy
hub / github.com/expr-lang/expr / ExampleAllowUndefinedVariables

Function ExampleAllowUndefinedVariables

expr_test.go:502–538  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

500}
501
502func 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
540func ExampleAllowUndefinedVariables_zero_value() {
541 code := `name == "" ? foo + bar : foo + name`

Callers

nothing calls this directly

Calls 5

EnvStruct · 0.92
AllowUndefinedVariablesFunction · 0.92
CompileFunction · 0.92
RunFunction · 0.92
PrintfMethod · 0.80

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…