如何直接从终端/命令行运行Go(lang)代码?

huangapple go评论93阅读模式
英文:

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 &quot;
package main
func main() {
println(&quot;hello&quot;)
}
&quot;
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 &lt; echo &quot;....&quot;

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 &quot;hello&quot;}
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目录中。

https://wiki.ubuntu.com/gorun

尽管它的初衷是用于脚本编写而不是作为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.

https://wiki.ubuntu.com/gorun

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

huangapple
  • 本文由 发表于 2015年1月3日 17:28:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/27753395.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定