Example_cel_Maps showcases map literals, size, field/key access, membership, and comparison as documented in https://celbyexample.com/maps/
()
| 135 | // Example_cel_Maps showcases map literals, size, field/key access, membership, and comparison |
| 136 | // as documented in https://celbyexample.com/maps/ |
| 137 | func Example_cel_Maps() { |
| 138 | exprs := []string{ |
| 139 | `{"a": 1, "b": 2}.a`, |
| 140 | `size({"a": 1, "b": 2})`, |
| 141 | `{1: "one", 2: "two"}[1]`, |
| 142 | `{"nested": {"a": 1}}.nested.a`, |
| 143 | `size({"a": 1, "b": 2, "c": 3})`, |
| 144 | `{"a": 1, "b": 2}.size()`, |
| 145 | `{"a": 1, "b": 2}["a"]`, |
| 146 | `{"a": 1, "b": 2}.a`, |
| 147 | `"a" in {"a": 1, "b": 2}`, |
| 148 | `"c" in {"a": 1, "b": 2}`, |
| 149 | `{"a": 1, "b": 2} == {"a": 1, "b": 2}`, |
| 150 | `{"a": 1} == {"a": 2}`, |
| 151 | } |
| 152 | |
| 153 | for _, expr := range exprs { |
| 154 | prg, err := cel.Compile(expr) |
| 155 | if err != nil { |
| 156 | log.Fatalf("cel.Compile() error for %q: %v", expr, err) |
| 157 | } |
| 158 | out, _, err := prg.Eval(cel.NoVars()) |
| 159 | if err != nil { |
| 160 | log.Fatalf("prg.Eval() error for %q: %v", expr, err) |
| 161 | } |
| 162 | fmt.Printf("%s -> %v\n", expr, out) |
| 163 | } |
| 164 | |
| 165 | // Output: |
| 166 | // {"a": 1, "b": 2}.a -> 1 |
| 167 | // size({"a": 1, "b": 2}) -> 2 |
| 168 | // {1: "one", 2: "two"}[1] -> one |
| 169 | // {"nested": {"a": 1}}.nested.a -> 1 |
| 170 | // size({"a": 1, "b": 2, "c": 3}) -> 3 |
| 171 | // {"a": 1, "b": 2}.size() -> 2 |
| 172 | // {"a": 1, "b": 2}["a"] -> 1 |
| 173 | // {"a": 1, "b": 2}.a -> 1 |
| 174 | // "a" in {"a": 1, "b": 2} -> true |
| 175 | // "c" in {"a": 1, "b": 2} -> false |
| 176 | // {"a": 1, "b": 2} == {"a": 1, "b": 2} -> true |
| 177 | // {"a": 1} == {"a": 2} -> false |
| 178 | } |