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

僤鯓⒐⒋嵵緔 提交于 2020-08-18 16:56:11

问题


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?


回答1:


Is this possible in golang? and why?

No, because golang is not that kind of language. It is intended to be compiled, not interpreted, so that the runtime does not contain any “string to code” transformer, or indeed knows what a syntactically correct program looks like.

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 causes computations to be done accordingly. The choice of the Go designers is only not to force a feature of such dubious interest and security on everyone who did not need it.




回答2:


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.




回答3:


There is no built-in eval. But it is possible to implement evaluation which will follow most of GoLang spec: eval (only expression, not a code) package 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 evaluated expression, but it requires pass them with theirs names to Eval method.




回答4:


have a look at Github Project: https://github.com/novalagung/golpal

It allows running more complex GO-Lang code Fragments but needs a 'temp' folder.




回答5:


This parsing example parses GO code at runtime:

package main

import (
    "fmt"
    "go/parser"
    "go/token"
)

func main() {
    fset := token.NewFileSet() // positions are relative to fset

    src := `package foo

import (
    "fmt"
    "time"
)

func bar() {
    fmt.Println(time.Now())
}`

    // Parse src but stop after processing the imports.
    f, err := parser.ParseFile(fset, "", src, parser.ImportsOnly)
    if err != nil {
        fmt.Println(err)
        return
    }

    // Print the imports from the file's AST.
    for _, s := range f.Imports {
        fmt.Println(s.Path.Value)
    }

}


来源:https://stackoverflow.com/questions/27680042/evaluate-execute-golang-code-expressions-like-js-eval

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!