MCPcopy Create free account
hub / github.com/cel-expr/cel-go / Example_globalOverload

Function Example_globalOverload

cel/cel_example_test.go:74–120  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

72}
73
74func Example_globalOverload() {
75 // The GlobalOverload example demonstrates how to define global overload function.
76 // Create the CEL environment with declarations for the input attributes and
77 // the desired extension functions. In many cases the desired functionality will
78 // be present in a built-in function.
79 e, err := cel.NewEnv(
80 // Identifiers used within this expression.
81 cel.Variable("i", cel.StringType),
82 cel.Variable("you", cel.StringType),
83 // Function to generate shake_hands between two people.
84 // shake_hands(i,you)
85 cel.Function("shake_hands",
86 cel.Overload("shake_hands_string_string", []*cel.Type{cel.StringType, cel.StringType}, cel.StringType,
87 cel.BinaryBinding(func(arg1, arg2 ref.Val) ref.Val {
88 return types.String(fmt.Sprintf("%v and %v are shaking hands.\n", arg1, arg2))
89 }),
90 ),
91 ),
92 )
93 if err != nil {
94 log.Fatalf("environment creation error: %s\n", err)
95 }
96
97 // Compile the expression.
98 ast, iss := e.Compile(`shake_hands(i,you)`)
99 if iss.Err() != nil {
100 log.Fatalln(iss.Err())
101 }
102
103 // Create the program.
104 prg, err := e.Program(ast)
105 if err != nil {
106 log.Fatalf("program creation error: %s\n", err)
107 }
108
109 // Evaluate the program against some inputs. Note: the details return is not used.
110 out, _, err := prg.Eval(map[string]any{
111 "i": "CEL",
112 "you": func() ref.Val { return types.String("world") },
113 })
114 if err != nil {
115 log.Fatalf("runtime error: %s\n", err)
116 }
117
118 fmt.Println(out)
119 // Output:CEL and world are shaking hands.
120}
121
122func Example_statefulOverload() {
123 // makeFetch produces a consistent function signature with a different function

Callers

nothing calls this directly

Calls 10

CompileMethod · 0.95
ProgramMethod · 0.95
NewEnvFunction · 0.92
VariableFunction · 0.92
FunctionFunction · 0.92
OverloadFunction · 0.92
BinaryBindingFunction · 0.92
StringTypeAlias · 0.92
ErrMethod · 0.80
EvalMethod · 0.65

Tested by

no test coverage detected