Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Evaluate/Execute Golang code/expressions like js' eval()

Tags:

go

eval

Is there a eval() like method on golang?

Evaluate/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;

The result of res will be:

200
4
27

Is this possible in golang? and why?

like image 423
kudarap Avatar asked Sep 06 '25 21:09

kudarap


1 Answers

Its perfectly possible. At least for expressions, which seems to be what you want:

Have a look at:

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

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

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

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

like image 93
iggy Avatar answered Sep 08 '25 12:09

iggy