Evaluate / execute code / Golang expressions such as js' eval ()

Is there an eval () method on golang?

Compute / execute JavaScript code / expressions:

var x = 10; var y = 20; var a = eval("x * y") + "<br>"; var b = eval("2 + 2") + "<br>"; var c = eval("x + 17") + "<br>"; var res = a + b + c; 

Res result will be:

 200 4 27 

Is this possible in the golang? and why?

+5
source share
4 answers

Is this possible in the golang? and why?

No, because the golang is not such a language. It is intended to be compiled, not interpreted, so the runtime does not contain a line-to-code transformer or does not know what a syntactically correct program looks like.

Please note that in Go, as in most other programming languages, you can write your own interpreter, that is, a function that takes a string and calls the corresponding calculations. The choice of Go designers is not to impose a feature of such dubious interest and safety for all who do not need it.

+5
source

It is quite possible. At least for the expressions you seem to want:

Take a look:

https://golang.org/src/go/types/eval.go

https://golang.org/src/go/constant/value.go

https://golang.org/pkg/go/types/#Scope

You need to create your own Package and Scope objects and Insert constants for the package area. Constants are created using types.NewConst by providing the appropriate type information.

+6
source

There is no built-in eval. But you can perform an evaluation that will follow most of the GoLang specification: the eval package (expression only, not code) on github / on godoc .

Example:

 import "github.com/apaxa-go/eval" ... src:="int8(1*(1+2))" expr,err:=eval.ParseString(src,"") if err!=nil{ return err } r,err:=expr.EvalToInterface(nil) if err!=nil{ return err } fmt.Printf("%v %T", r, r) // "3 int8" 

It is also possible to use variables in a computed expression, but this requires passing them with their names to the Eval method.

+2
source

take a look at the Github project: https://github.com/novalagung/golpal

It allows you to run more complex GO-Lang code snippets, but needs the temp folder.

0
source

Source: https://habr.com/ru/post/1210007/


All Articles