Evaluated/Executing Golang Code/Expression Like JavaScript's eval()
JavaScript's eval() method allows for the evaluation and execution of code/expressions dynamically. This raises the question of whether a similar functionality exists in Go.
Solution
Yes, it is possible to evaluate and execute Go code/expressions, particularly expressions, using the eval.go package from the Go standard library.
To achieve this, the following workflow is required:
Example
Consider the JavaScript code provided:
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 following Go code demonstrates how to evaluate these expressions:
import ( "fmt" "go/types" ) func main() { // Create a package pkg := types.NewPackage("main", "go.example.org/eval") // Create a scope scope := types.NewScope(pkg, types.Universe) // Insert constants scope.Insert(types.NewConst(types.NewVar(scope, "x", types.Int), types.Typ[types.Int], 10)) scope.Insert(types.NewConst(types.NewVar(scope, "y", types.Int), types.Typ[types.Int], 20)) // Evaluate expressions res := evalExpression(scope, pkg) fmt.Println(res) // 200\n4\n27 } func evalExpression(scope *types.Scope, pkg *types.Package) string { expr, _ := types.ParseExpr("x * y + \"\n\"") result, _ := eval.Eval(expr, pkg, scope) return result.String() }
The above is the detailed content of Is there a Go equivalent to JavaScript's eval() function for dynamic code evaluation?. For more information, please follow other related articles on the PHP Chinese website!