Evaluate formula in Go

前端 未结 8 990
梦如初夏
梦如初夏 2021-01-02 12:46

Using Go (golang) I\'d like to take a string with a formula and evaluate it with pre-defined values. Here\'s a way to do it with python\'s parser module:

<
8条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-02 13:21

    You will probably need to resort to a library that interprets math statements or have to write your own parser. Python being a dynamic language can parse and execute python code at runtime. Standard Go cannot do that.

    If you want to write a parser on your own, the go package will be of help. Example (On play):

    import (
        "go/ast"
        "go/parser"
        "go/token"
    )
    
    func main() {
        fs := token.NewFileSet()
        tr, _ := parser.ParseExpr("(3-1) * 5")
        ast.Print(fs, tr)
    }
    

    The resulting AST (Abstract Syntax Tree) can then be traversed and interpreted as you choose (handling '+' tokens as addition for the now stored values, for example).

提交回复
热议问题