| FazBrowse GitHub Viewer | Trending | | Home |
| Tools: [Download Repo ZIP] [Original HTTPS Page] |
This package is not in the latest version of its module.
Go to latest Published: Feb 14, 2026 License: MITThe Go module system was introduced in Go 1.11 and is the official dependency management solution for Go.
Redistributable licenses place minimal restrictions on how software can be used, modified, and redistributed.
Modules with tagged versions give importers more predictable builds.
When a project reaches major version v1 it is considered stable.
This section is empty.
This section is empty.
Compile parses and compiles given input expression to bytecode program.
Example ¶
package main
import (
"fmt"
"github.com/expr-lang/expr"
)
func main() {
env := map[string]any{
"foo": 1,
"bar": 99,
}
program, err := expr.Compile("foo in 1..99 and bar in 1..99", expr.Env(env))
if err != nil {
fmt.Printf("%v", err)
return
}
output, err := expr.Run(program, env)
if err != nil {
fmt.Printf("%v", err)
return
}
fmt.Printf("%v", output)
}
Output: true
Eval parses, compiles and runs given input.
Example ¶
package main
import (
"fmt"
"github.com/expr-lang/expr"
)
func main() {
output, err := expr.Eval("greet + name", map[string]any{
"greet": "Hello, ",
"name": "world!",
})
if err != nil {
fmt.Printf("err: %v", err)
return
}
fmt.Printf("%v", output)
}
Output: Hello, world!
package main
import (
"fmt"
"github.com/expr-lang/expr"
)
func main() {
// Bytes literal returns []byte.
output, err := expr.Eval(`b"abc"`, nil)
if err != nil {
fmt.Printf("%v", err)
return
}
fmt.Printf("%v", output)
}
Output: [97 98 99]
package main
import (
"fmt"
"github.com/expr-lang/expr"
)
func main() {
_, err := expr.Eval(`map(1..3, {1 % (# - 3)})`, nil)
fmt.Print(err)
}
Output: runtime error: integer divide by zero (1:14) | map(1..3, {1 % (# - 3)}) | .............^
Option for configuring config.
func AllowUndefinedVariables() Option
AllowUndefinedVariables allows to use undefined variables inside expressions. This can be used with expr.Env option to partially define a few variables.
Example ¶
package main
import (
"fmt"
"github.com/expr-lang/expr"
)
func main() {
code := `name == nil ? "Hello, world!" : sprintf("Hello, %v!", name)`
env := map[string]any{
"sprintf": fmt.Sprintf,
}
options := []expr.Option{
expr.Env(env),
expr.AllowUndefinedVariables(), // Allow to use undefined variables.
}
program, err := expr.Compile(code, options...)
if err != nil {
fmt.Printf("%v", err)
return
}
output, err := expr.Run(program, env)
if err != nil {
fmt.Printf("%v", err)
return
}
fmt.Printf("%v\n", output)
env["name"] = "you" // Define variables later on.
output, err = expr.Run(program, env)
if err != nil {
fmt.Printf("%v", err)
return
}
fmt.Printf("%v\n", output)
}
Output: Hello, world! Hello, you!
package main
import (
"fmt"
"github.com/expr-lang/expr"
)
func main() {
code := `name == "" ? foo + bar : foo + name`
// If environment has different zero values, then undefined variables
// will have it as default value.
env := map[string]string{}
options := []expr.Option{
expr.Env(env),
expr.AllowUndefinedVariables(), // Allow to use undefined variables.
}
program, err := expr.Compile(code, options...)
if err != nil {
fmt.Printf("%v", err)
return
}
env = map[string]string{
"foo": "Hello, ",
"bar": "world!",
}
output, err := expr.Run(program, env)
if err != nil {
fmt.Printf("%v", err)
return
}
fmt.Printf("%v", output)
}
Output: Hello, world!
package main
import (
"fmt"
"github.com/expr-lang/expr"
"github.com/expr-lang/expr/test/mock"
)
func main() {
code := `words == "" ? Split("foo,bar", ",") : Split(words, ",")`
// Env is map[string]string type on which methods are defined.
env := mock.MapStringStringEnv{}
options := []expr.Option{
expr.Env(env),
expr.AllowUndefinedVariables(), // Allow to use undefined variables.
}
program, err := expr.Compile(code, options...)
if err != nil {
fmt.Printf("%v", err)
return
}
output, err := expr.Run(program, env)
if err != nil {
fmt.Printf("%v", err)
return
}
fmt.Printf("%v", output)
}
Output: [foo bar]
func AsBool() Option
AsBool tells the compiler to expect a boolean result.
Example ¶
package main
import (
"fmt"
"github.com/expr-lang/expr"
)
func main() {
env := map[string]int{
"foo": 0,
}
program, err := expr.Compile("foo >= 0", expr.Env(env), expr.AsBool())
if err != nil {
fmt.Printf("%v", err)
return
}
output, err := expr.Run(program, env)
if err != nil {
fmt.Printf("%v", err)
return
}
fmt.Printf("%v", output.(bool))
}
Output: true
package main
import (
"fmt"
"github.com/expr-lang/expr"
)
func main() {
env := map[string]any{
"foo": 0,
}
_, err := expr.Compile("foo + 42", expr.Env(env), expr.AsBool())
fmt.Printf("%v", err)
}
Output: expected bool, but got int
func AsFloat64() Option
AsFloat64 tells the compiler to expect a float64 result.
Example ¶
package main
import (
"fmt"
"github.com/expr-lang/expr"
)
func main() {
program, err := expr.Compile("42", expr.AsFloat64())
if err != nil {
fmt.Printf("%v", err)
return
}
output, err := expr.Run(program, nil)
if err != nil {
fmt.Printf("%v", err)
return
}
fmt.Printf("%v", output.(float64))
}
Output: 42
package main
import (
"fmt"
"github.com/expr-lang/expr"
)
func main() {
_, err := expr.Compile(`!!true`, expr.AsFloat64())
fmt.Printf("%v", err)
}
Output: expected float64, but got bool
func AsInt() Option
AsInt tells the compiler to expect an int result.
Example ¶
package main
import (
"fmt"
"github.com/expr-lang/expr"
)
func main() {
program, err := expr.Compile("42", expr.AsInt())
if err != nil {
fmt.Printf("%v", err)
return
}
output, err := expr.Run(program, nil)
if err != nil {
fmt.Printf("%v", err)
return
}
fmt.Printf("%T(%v)", output, output)
}
Output: int(42)
func AsInt64() Option
AsInt64 tells the compiler to expect an int64 result.
Example ¶
package main
import (
"fmt"
"github.com/expr-lang/expr"
)
func main() {
env := map[string]any{
"rating": 5.5,
}
program, err := expr.Compile("rating", expr.Env(env), expr.AsInt64())
if err != nil {
fmt.Printf("%v", err)
return
}
output, err := expr.Run(program, env)
if err != nil {
fmt.Printf("%v", err)
return
}
fmt.Printf("%v", output.(int64))
}
Output: 5
AsKind tells the compiler to expect kind of the result.
Example ¶
package main
import (
"fmt"
"reflect"
"github.com/expr-lang/expr"
)
func main() {
program, err := expr.Compile("{a: 1, b: 2}", expr.AsKind(reflect.Map))
if err != nil {
fmt.Printf("%v", err)
return
}
output, err := expr.Run(program, nil)
if err != nil {
fmt.Printf("%v", err)
return
}
fmt.Printf("%v", output)
}
Output: map[a:1 b:2]
ConstExpr defines func expression as constant. If all argument to this function is constants, then it can be replaced by result of this func call on compile step.
Example ¶
package main
import (
"fmt"
"github.com/expr-lang/expr"
)
func fib(n int) int {
if n <= 1 {
return n
}
return fib(n-1) + fib(n-2)
}
func main() {
code := `[fib(5), fib(3+3), fib(dyn)]`
env := map[string]any{
"fib": fib,
"dyn": 0,
}
options := []expr.Option{
expr.Env(env),
expr.ConstExpr("fib"), // Mark fib func as constant expression.
}
program, err := expr.Compile(code, options...)
if err != nil {
fmt.Printf("%v", err)
return
}
// Only fib(5) and fib(6) calculated on Compile, fib(dyn) can be called at runtime.
env["dyn"] = 7
output, err := expr.Run(program, env)
if err != nil {
fmt.Printf("%v", err)
return
}
fmt.Printf("%v\n", output)
}
Output: [5 8 13]
func DisableAllBuiltins() Option
DisableAllBuiltins disables all builtins.
DisableBuiltin disables builtin function.
func DisableIfOperator() Option
DisableIfOperator disables the `if ... else ...` operator syntax so a custom function named `if(...)` can be used without conflicts.
func DisableShortCircuit() Option
DisableShortCircuit turns short circuit off.
EnableBuiltin enables builtin function.
Env specifies expected input of env for type checks. If struct is passed, all fields will be treated as variables, as well as all fields of embedded structs and struct itself. If map is passed, all items will be treated as variables. Methods defined on this type will be available as functions.
Example ¶
package main
import (
"fmt"
"github.com/expr-lang/expr"
)
func main() {
type Segment struct {
Origin string
}
type Passengers struct {
Adults int
}
type Meta struct {
Tags map[string]string
}
type Env struct {
Meta
Segments []*Segment
Passengers *Passengers
Marker string
}
code := `all(Segments, {.Origin == "MOW"}) && Passengers.Adults > 0 && Tags["foo"] startsWith "bar"`
program, err := expr.Compile(code, expr.Env(Env{}))
if err != nil {
fmt.Printf("%v", err)
return
}
env := Env{
Meta: Meta{
Tags: map[string]string{
"foo": "bar",
},
},
Segments: []*Segment{
{Origin: "MOW"},
},
Passengers: &Passengers{
Adults: 2,
},
Marker: "test",
}
output, err := expr.Run(program, env)
if err != nil {
fmt.Printf("%v", err)
return
}
fmt.Printf("%v", output)
}
Output: true
package main
import (
"fmt"
"strings"
"github.com/expr-lang/expr"
)
func main() {
type Internal struct {
Visible string
Hidden string `expr:"-"`
}
type environment struct {
Visible string
Hidden string `expr:"-"`
HiddenInternal Internal `expr:"-"`
VisibleInternal Internal
}
env := environment{
Hidden: "First level secret",
HiddenInternal: Internal{
Visible: "Second level secret",
Hidden: "Also hidden",
},
VisibleInternal: Internal{
Visible: "Not a secret",
Hidden: "Hidden too",
},
}
hiddenValues := []string{
`Hidden`,
`HiddenInternal`,
`HiddenInternal.Visible`,
`HiddenInternal.Hidden`,
`VisibleInternal["Hidden"]`,
}
for _, expression := range hiddenValues {
output, err := expr.Eval(expression, env)
if err == nil || !strings.Contains(err.Error(), "cannot fetch") {
fmt.Printf("unexpected output: %v; err: %v\n", output, err)
return
}
fmt.Printf("%q is hidden as expected\n", expression)
}
visibleValues := []string{
`Visible`,
`VisibleInternal`,
`VisibleInternal["Visible"]`,
}
for _, expression := range visibleValues {
_, err := expr.Eval(expression, env)
if err != nil {
fmt.Printf("unexpected error: %v\n", err)
return
}
fmt.Printf("%q is visible as expected\n", expression)
}
testWithIn := []string{
`not ("Hidden" in $env)`,
`"Visible" in $env`,
`not ("Hidden" in VisibleInternal)`,
`"Visible" in VisibleInternal`,
}
for _, expression := range testWithIn {
val, err := expr.Eval(expression, env)
shouldBeTrue, ok := val.(bool)
if err != nil || !ok || !shouldBeTrue {
fmt.Printf("unexpected result; value: %v; error: %v\n", val, err)
return
}
}
}
Output: "Hidden" is hidden as expected "HiddenInternal" is hidden as expected "HiddenInternal.Visible" is hidden as expected "HiddenInternal.Hidden" is hidden as expected "VisibleInternal[\"Hidden\"]" is hidden as expected "Visible" is visible as expected "VisibleInternal" is visible as expected "VisibleInternal[\"Visible\"]" is visible as expected
package main
import (
"fmt"
"github.com/expr-lang/expr"
)
func main() {
env := struct {
FirstWord string
Separator string `expr:"Space"`
SecondWord string `expr:"second_word"`
}{
FirstWord: "Hello",
Separator: " ",
SecondWord: "World",
}
output, err := expr.Eval(`FirstWord + Space + second_word`, env)
if err != nil {
fmt.Printf("%v", err)
return
}
fmt.Printf("%v", output)
}
Output: Hello World
Function adds function to list of functions what will be available in expressions.
MaxNodes sets the maximum number of nodes allowed in the expression. By default, the maximum number of nodes is conf.DefaultMaxNodes. If MaxNodes is set to 0, the node budget check is disabled.
Operator allows to replace a binary operator with a function.
Example ¶
package main
import (
"fmt"
"time"
"github.com/expr-lang/expr"
)
func main() {
code := `
Now() > CreatedAt &&
(Now() - CreatedAt).Hours() > 24
`
type Env struct {
CreatedAt time.Time
Now func() time.Time
Sub func(a, b time.Time) time.Duration
After func(a, b time.Time) bool
}
options := []expr.Option{
expr.Env(Env{}),
expr.Operator(">", "After"),
expr.Operator("-", "Sub"),
}
program, err := expr.Compile(code, options...)
if err != nil {
fmt.Printf("%v", err)
return
}
env := Env{
CreatedAt: time.Date(2018, 7, 14, 0, 0, 0, 0, time.UTC),
Now: func() time.Time { return time.Now() },
Sub: func(a, b time.Time) time.Duration { return a.Sub(b) },
After: func(a, b time.Time) bool { return a.After(b) },
}
output, err := expr.Run(program, env)
if err != nil {
fmt.Printf("%v", err)
return
}
fmt.Printf("%v", output)
}
Output: true
package main
import (
"fmt"
"github.com/expr-lang/expr"
)
func main() {
type Decimal struct{ N float64 }
code := `A + B - C`
type Env struct {
A, B, C Decimal
Sub func(a, b Decimal) Decimal
Add func(a, b Decimal) Decimal
}
options := []expr.Option{
expr.Env(Env{}),
expr.Operator("+", "Add"),
expr.Operator("-", "Sub"),
}
program, err := expr.Compile(code, options...)
if err != nil {
fmt.Printf("Compile error: %v", err)
return
}
env := Env{
A: Decimal{3},
B: Decimal{2},
C: Decimal{1},
Sub: func(a, b Decimal) Decimal { return Decimal{a.N - b.N} },
Add: func(a, b Decimal) Decimal { return Decimal{a.N + b.N} },
}
output, err := expr.Run(program, env)
if err != nil {
fmt.Printf("%v", err)
return
}
fmt.Printf("%v", output)
}
Output: {4}
Patch adds visitor to list of visitors what will be applied before compiling AST to bytecode.
Example ¶
package main
import (
"fmt"
"github.com/expr-lang/expr"
"github.com/expr-lang/expr/ast"
)
type patcher struct{}
func (p *patcher) Visit(node *ast.Node) {
switch n := (*node).(type) {
case *ast.MemberNode:
ast.Patch(node, &ast.CallNode{
Callee: &ast.IdentifierNode{Value: "get"},
Arguments: []ast.Node{n.Node, n.Property},
})
}
}
func main() {
program, err := expr.Compile(
`greet.you.world + "!"`,
expr.Patch(&patcher{}),
)
if err != nil {
fmt.Printf("%v", err)
return
}
env := map[string]any{
"greet": "Hello",
"get": func(a, b string) string {
return a + ", " + b
},
}
output, err := expr.Run(program, env)
if err != nil {
fmt.Printf("%v", err)
return
}
fmt.Printf("%v", output)
}
Output: Hello, you, world!
Timezone sets default timezone for date() and now() builtin functions.
Example ¶
package main
import (
"fmt"
"github.com/expr-lang/expr"
)
func main() {
program, err := expr.Compile(`now().Location().String()`, expr.Timezone("Asia/Kamchatka"))
if err != nil {
fmt.Printf("%v", err)
return
}
output, err := expr.Run(program, nil)
if err != nil {
fmt.Printf("%v", err)
return
}
fmt.Printf("%v", output)
}
Output: Asia/Kamchatka
func WarnOnAny() Option
WarnOnAny tells the compiler to warn if expression return any type.
Example ¶
package main
import (
"fmt"
"github.com/expr-lang/expr"
)
func main() {
// Arrays always have []any type. The expression return type is any.
// AsInt() instructs compiler to expect int or any, and cast to int,
// if possible. WarnOnAny() instructs to return an error on any type.
_, err := expr.Compile(`[42, true, "yes"][0]`, expr.AsInt(), expr.WarnOnAny())
fmt.Printf("%v", err)
}
Output: expected int, but got interface {}
WithContext passes context to all functions calls with a context.Context argument.
Example ¶
package main
import (
"context"
"fmt"
"time"
"github.com/expr-lang/expr"
)
func main() {
env := map[string]any{
"fn": func(ctx context.Context, _, _ int) int {
// An infinite loop that can be canceled by context.
for {
select {
case <-ctx.Done():
return 42
}
}
},
"ctx": context.TODO(), // Context should be passed as a variable.
}
program, err := expr.Compile(`fn(1, 2)`,
expr.Env(env),
expr.WithContext("ctx"), // Pass context variable name.
)
if err != nil {
fmt.Printf("%v", err)
return
}
// Cancel context after 100 milliseconds.
ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond*100)
defer cancel()
// After program is compiled, context can be passed to Run.
env["ctx"] = ctx
// Run will return 42 after 100 milliseconds.
output, err := expr.Run(program, env)
if err != nil {
fmt.Printf("%v", err)
return
}
fmt.Printf("%v", output)
}
Output: 42
| Path | Synopsis |
|---|---|
|
debug
module
|
|
|
internal
|
|
|
difflib
Package difflib is a partial port of Python difflib module.
|
Package difflib is a partial port of Python difflib module. |
|
spew
Package spew implements a deep pretty printer for Go data structures to aid in debugging.
|
Package spew implements a deep pretty printer for Go data structures to aid in debugging. |
|
testify/assert
Package assert provides a set of comprehensive testing tools for use with the normal Go testing system.
|
Package assert provides a set of comprehensive testing tools for use with the normal Go testing system. |
|
testify/assert/internal/unsafetests
This package exists just to isolate tests that reference the unsafe package.
|
This package exists just to isolate tests that reference the unsafe package. |
|
testify/require
Package require implements the same assertions as the `assert` package but stops test execution when a test fails.
|
Package require implements the same assertions as the `assert` package but stops test execution when a test fails. |
|
value
Package value provides a Patcher that uses interfaces to allow custom types that can be represented as standard go values to be used more easily in expressions.
|
Package value provides a Patcher that uses interfaces to allow custom types that can be represented as standard go values to be used more easily in expressions. |
|
repl
module
|
|
|
test
|
|
|
examples
command
|
|
|
gen
command
|
|
|
func_types
command
|
|
|
runtime/helpers
command
|
| Back | FazBrowse Home | New Git URL |