Files
expr/patcher/value/value_example_test.go
Ryan BullockandGitHub 3bda06349a Patcher and interfaces for custom types to be used in expressions as standard go types (#487)
* A bultin patcher providing interfaces for custom types that can be represented as standard go types for expressions.

* Move node creation inside of loop.

* Reorder imports. Fix some formatting.

* Rename expr function from 'getExprValue' to '$patcher_value_getter'.

* Move to expr-lang

* Rename Patcher to ValueGetter

* Remove use of Expr in naming

* Rename interface functions to use 'AsType()' convention

* Document motivation and an example use case

* Add example usage to AsAny()

* Move under patcher directory

* Fix reference to old import path
2023-12-26 16:01:55 +01:00

43 lines
609 B
Go

package value_test
import (
"fmt"
"github.com/expr-lang/expr"
"github.com/expr-lang/expr/patcher/value"
"github.com/expr-lang/expr/vm"
)
type myInt struct {
Int int
}
func (v *myInt) AsInt() int {
return v.Int
}
func (v *myInt) AsAny() any {
return v.Int
}
func ExampleAnyValuer() {
env := make(map[string]any)
env["ValueOne"] = &myInt{1}
env["ValueTwo"] = &myInt{2}
program, err := expr.Compile("ValueOne + ValueTwo", expr.Env(env), value.ValueGetter)
if err != nil {
panic(err)
}
out, err := vm.Run(program, env)
if err != nil {
panic(err)
}
fmt.Println(out)
// Output: 3
}