dongshimao7115 2016-07-28 19:29
浏览 85

评估字符串中的布尔表达式-Go

I have a boolean expression in string format, example:

name := "Fred"

type := "Person"

I want to evaluate this expression as true or false.

exp := "(name == Fred) && (type == Person)"

Eventually, I would like to be able to execute conditional statements such as:

if (exp) {
    ...
}

However, from research this is not something Go supports out of the box. I have seen suggestions on using AST to parse and evaluate. But, I am fairly new to go and especially AST, thus not sure how to go about that. Can someone please provide any guidance on how I may go about evaluating a string boolean expression? I have not come across any packages that support this entirely.

  • 写回答

1条回答 默认 最新

  • duanrang3357 2016-07-28 23:41
    关注

    The following is true in theory. But since you're using Go if you can use Go syntax then you can use Go's parser and AST. I don't see any code that can evaluate a Go AST at runtime. But you could probably write one that supported the parts you wanted. Then you'd have a Go interpreter.

    The following is what you need to do to support any random expression syntax:

    You are going to want to lex and parse. Build an AST (Abstract Syntax Tree) in memory. Then evaluate it.

    Your tree nodes might be (my Go syntax is way wrong for this):

     Scope {Tree {
      Assignment { Symbol: "name", Symbol: "_literal_1" }
      Assignment { Symbol: "exp", Value: Tree: {
        AndOperation { Tree{...}, Tree{...} }
      }
    }
    

    Etc.

    Then your program can traverse your AST directly or you can write it into bytecode form, but that's really only useful if you want it to be smaller and easy to cache for later.

    评论

报告相同问题?

悬赏问题

  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)