Evaluate formula in Go

前端 未结 8 1019
梦如初夏
梦如初夏 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:11

    With this code you can evaluate dynamically any formula and return true or false:

    package main
    
    import (
        "go/token"
        "go/types"
    )
    
    func main() {
        fs := token.NewFileSet()
        tv, err := types.Eval(fs, nil, token.NoPos, "(1 + 4) >= 5")
        if err != nil {
            panic(err)
        }
        println(tv.Value.String())
    }
    

提交回复
热议问题