大家好,欢迎来到IT知识分享网。
关注公众号 “OpenSourceDaily” ,每天推荐给你优秀开源项目
今天为 Go 语言爱好者推荐一个脚本语言:Tengo,这是用 Go 语言实现的小型,动态,快速,安全的脚本语言。项目地址:https://github.com/d5/tengo,目前 Star 数:1.7k+。
Tengo 既快速又安全,因为它是用 native Go 编写的基于堆栈的 VM 上作为字节码编译/执行的。
特性
该语言的特性如下:
- 简单易读的语法
- 带类型强制的动态输入
- 高阶函数和闭包
- 不变值
- 可安全嵌入和扩展
- 用 native Go 编写的编译器/运行时(无外部 deps 或 cgo)
- 可执行为独立语言或 REPL
- 案例:规则引擎,状态机,数据管道,翻译器(如 tengo 到 lua)
性能如何呢?
使用
Tengo 支持几种使用方式。
1)作为 Go 包,嵌入 Go 中使用,比如:
package main
import (
"context"
"fmt"
"github.com/d5/tengo/v2"
)
func main() {
// Tengo script code
src := `
each := func(seq, fn) {
for x in seq { fn(x) }
}
sum := 0
mul := 1
each([a, b, c, d], func(x) {
sum += x
mul *= x
})`
// create a new Script instance
script := tengo.NewScript([]byte(src))
// set values
_ = script.Add("a", 1)
_ = script.Add("b", 9)
_ = script.Add("c", 8)
_ = script.Add("d", 4)
// run the script
compiled, err := script.RunContext(context.Background())
if err != nil {
panic(err)
}
// retrieve values
sum := compiled.Get("sum")
mul := compiled.Get("mul")
fmt.Println(sum, mul) // "22 288"
}
编译运行使用 Go 来处理。需要按照 Tengo:
go get github.com/d5/tengo/v2
2)作为独立脚本使用
先安装 Tengo CLI:
go get github.com/d5/tengo/cmd/tengo
写下如下脚本:
fmt := import("fmt")
// 注意 p 是小写的
fmt.println("Hello Tengo!")
保存为:hello.tengo,之后执行如下命令:
tengo hello.tengo
输出:
Hello Tengo!
3)类似 Python,REPL 方式运行
很简单,输入 tengo 回车,然后交互式输入:
>> fmt := import("fmt")
{printf: , println: , sprintf: , print: , __module_name__: "fmt"}
>> fmt.println("Hello Tengo!")
Hello Tengo!
>>
相关文档
目前官方提供了如下文档,通过这些文档可以看到该脚本语言支持的功能。
- 语言语法:https://github.com/d5/tengo/blob/master/docs/tutorial.md
- 对象类型:https://github.com/d5/tengo/blob/master/docs/objects.md
- 运行时类型:https://github.com/d5/tengo/blob/master/docs/runtime-types.md
- 操作符:https://github.com/d5/tengo/blob/master/docs/operators.md
- 内置函数:https://github.com/d5/tengo/blob/master/docs/builtins.md
- 互通性:https://github.com/d5/tengo/blob/master/docs/interoperability.md
- Tengo 命令行:https://github.com/d5/tengo/blob/master/docs/tengo-cli.md
- 标准库:https://github.com/d5/tengo/blob/master/docs/stdlib.md
另外还提供了 VSCode 和 Atom 的语法高亮插件。
目前标准库不多,只有如下几个:
在线 Playground
官方还提供了在线试验的 Playground:https://tengolang.com,有兴趣的可以试试!
文末「阅读原文」可直达项目首页。
今天的项目大家觉得怎么样吗?如果你喜欢,请在文章底部留言、点赞或关注转发,你的支持就是我持续更新的最大动力!
推荐阅读
- 4月份Github上最热门的开源项目
OpenSourceDaily – 送给爱开源的你
Git · GitHub · GitLab · Gitee
免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://haidsoft.com/158323.html