simple and powerful YA on Go

simple and powerful YA on Go

Hello, Habre!

Today I want to share with you a discovery that may be useful for those who work with the Go programming language and are looking for a reliable tool for evaluating expressions. It will be about the expr library from Anton Medvedev.

What is expr?

Expr is a library for evaluating expressions in Go. With it, you can parse, test, and interpret simple Go expressions without the need for external dependencies or complex constructs.

Main features:

  1. Speed ​​action: The library is optimized for high performance

  2. Security: Expr provides a secure execution context, keeping your programs safe from potential threats.

  3. Typification: You don’t need to worry about types – Expr takes them into account when evaluating expressions

  4. Support functions: You can define your own functions and use them in expressions.

  5. Flexibility: The library can be easily integrated into your project and customized according to your requirements.

How does it work?

Let’s look at a simple usage example:

package main

import (
	"fmt"
	"github.com/antonmedv/expr"
)

func main() {
	env := map[string]interface{}{
		"foo": 1,
		"bar": 2,
	}

	code, err := expr.Compile("foo + bar", expr.Env(env))
	if err != nil {
		panic(err)
	}

	out, err := expr.Run(code, env)
	if err != nil {
		panic(err)
	}

	fmt.Println(out) // вывод: 3
}

In this example, we create a simple expression “foo + bar” and then evaluate it using the given environment env. The result will be the number 3.

Why might this be necessary?

Expr can be useful in various scenarios:

  • Dynamic configuration: You can allow users of your application to specify configuration options using expressions.

  • Business rule logic: Expr allows you to interpret complex business rules specified by users.

  • Calculation on the fly: You don’t have to wait for the program to be recompiled to change any calculation logic.

Conclusion

Expr is a powerful and flexible tool for working with expressions in Go. It is easily integrated into various projects and allows safe interpretation of statements without additional costs. If you work in Go and are looking for a solution for working with expressions, I recommend that you pay attention to this library!

Happy coding to all!

Related posts