Goexpr is a Go package that evaluates mathematical expressions. Values can be constants, or variables whose values are provided at evaluation time. Goexpr is inspired by MathJS.
Being able to evaluate basic mathematical expressions is useful in analytics, but Go is not a scripting language with eval
. A simple, pluggable math library abstracts out the mechanics of evaluation from the application requiring it.
- Supports basic algebraic operations.
- Not regex-based, parses with Go's
ast
. - Safe, restricted to a subset of language-defined syntax.
- No external dependencies.
Install:
go get github.com/crsmithdev/goxpr
Evaluate (a + b) / 2
, where a=3
and b=1
:
import "github.com/crsmithdev/goexpr"
parsed, _ := goexpr.Parse("(a + b) / 2")
result, _ := goexpr.Evaluate(parsed, map[string]float64{
"a": 3,
"b": 1,
})
fmt.Println("result: %d", result)
result: 2
API documentation is on Godoc.
After cloning, build:
make
Run tests:
make test
Run tests automatically on write:
make test-auto
Run tests with coverage:
make test-cov
View HTML coverage report:
make html-cov
- Additional operators and functions
- Additional examples