英文:
How to run Go(lang) code directly from terminal/command line?
问题
我想直接从终端/命令行运行简单的Go代码。例如:
package main
func main() {
println("hello")
}
然而,Go语言只允许从文件中执行代码。所以也许有一些方法可以模拟它?像这样:
go run file.go < echo "...."
但在上述操作之后,不应该有任何文件残留。
英文:
I want to run simple go code directly from terminal/command line. For example:
go run "
package main
func main() {
println("hello")
}
"
hello
However golang allows code execution only from file. So maybe there are some ways how to emulate it? Like this:
go run file.go < echo "...."
But there should be no files after actions above.
答案1
得分: 7
在命令行中,只有像go-repl这样的项目才能编译/运行多行Go源代码而不留下任何.go
文件。另一个选择是gore:
$ gore
输入一行或多行代码,然后按下ctrl-D
func test() string {return "hello";}
println(test())
^D
---------------------------------
hello
(其他类似repl的解决方案列在"Does Go provide REPL?"中)
或者你可以开发一个Go包装器,在内部创建一个源代码并运行它,然后再删除它。
英文:
In command-line, only a project like go-repl would compile/run a multi-line go source code without leaving any .go
file behind.
An alternative: gore:
$ gore
Enter one or more lines and hit ctrl-D
func test() string {return "hello"}
println(test())
^D
---------------------------------
hello
(Other repl-like solution are listed in "Does Go provide REPL?")
Or you would need to develop a go wrapper which would internally create a source code and go run it, before deleting it.
答案2
得分: 1
Ubuntu有一个名为gorun
的工具,非常适合小型脚本。它可以即时编译脚本,并将二进制文件缓存到/tmp目录中。
尽管它的初衷是用于脚本编写而不是作为REPL(交互式解释器),但你可以以各种方式使用它。
虽然gorun
来自Ubuntu社区,但由于它使用了纯净的Go源代码,所以它应该可以在任何Linux发行版上使用。
你可以通过以下命令获取gorun
:
$ go get launchpad.net/gorun
英文:
Ubuntu has a gorun
tool which works well for small scripts. It compiles scripts on the fly, caching the binaries in /tmp.
Although it's intended for scripting and not as a REPL, you could use it in various ways.
Although gorun
has come from the Ubuntu community, it should work on any Linux distro because it uses vanilla Go source code via
$ go get launchpad.net/gorun
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论