golang 如何eval函数计算算术表达式的功能
时间: 2023-02-08 21:40:35 浏览: 89
Golang 没有内置的 eval 函数来计算算术表达式。但是可以使用第三方库如 "github.com/Knetic/govaluate" 或 "github.com/antonmedv/expr" 来实现这个功能。例如,使用 "github.com/Knetic/govaluate" 库可以这样计算算术表达式:
```
package main
import (
"fmt"
"github.com/Knetic/govaluate"
)
func main() {
expression, _ := govaluate.NewEvaluableExpression("1+2*3")
result, _ := expression.Evaluate(nil)
fmt.Println(result) // 7
}
```
相关问题
golang eval函数
A: Go语言本身没有提供类似于eval函数的功能。但是可以使用Go语言自带的go/ast包和go/parser包来解析代码字符串并生成抽象语法树(AST),然后使用go/types包对生成的AST进行类型检查和求值。以下是一个简单的例子:
```go
package main
import (
"fmt"
"go/ast"
"go/parser"
"go/token"
"go/types"
)
func main() {
expr := "1 + 2 * 3"
fset := token.NewFileSet()
node, err := parser.ParseExpr(expr)
if err != nil {
panic(err)
}
info := types.Info{
Types: make(map[ast.Expr]types.TypeAndValue),
Definitions: make(map[*ast.Ident]types.Object),
Uses: make(map[*ast.Ident]types.Object),
}
types.Check(expr, fset, []*ast.File{ast.NewFile(fset, token.NoPos, &ast.File{Name: ast.NewIdent("main")}, []*ast.Decl{&ast.ExprStmt{X: node}})}, &info)
val := info.Types[node].Value.String()
fmt.Println(val)
}
```
该示例将解析字符串"1 + 2 * 3"并计算其值。在实际场景中,使用eval功能可能会存在安全隐患,因此应谨慎使用。
golang 计算 函数每秒性能
要计算 Golang 函数每秒性能,您可以使用 Go 的内置 `time` 包和 `testing` 包。具体步骤如下:
1. 创建测试函数,使用 `testing.B` 类型参数并使用 `for` 循环来运行测试函数多次,例如:
```go
func BenchmarkMyFunction(b *testing.B) {
for i := 0; i < b.N; i++ {
// call your function here
myFunction()
}
}
```
2. 在命令行中运行测试函数,并使用 `-bench` 标志指定测试函数的名称,例如:
```bash
go test -bench=MyFunction
```
3. 运行测试函数后,输出的结果将包括每秒测试运行的次数和每次运行所需的平均时间。例如:
```
BenchmarkMyFunction-4 1000000000 0.277 ns/op
```
这意味着 `MyFunction` 函数每秒运行一亿次,每次运行平均需要 0.277 纳秒的时间。
请注意,测试结果可能会因计算机性能、操作系统和其他因素而异。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)