评估字符串中的布尔表达式-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.

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.