普通网友 2014-05-28 23:18
浏览 1
已采纳

在Go中评估公式

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:

x = 8
code = parser.expr("(x + 2) / 10").compile()
print eval(code)
# prints 1

Any idea how to do it with Go?

  • 写回答

7条回答 默认 最新

  • doufei2355 2014-05-28 23:27
    关注

    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).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(6条)

报告相同问题?

悬赏问题

  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)