简体   繁体   English

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

[英]How to run Go(lang) code directly from terminal/command line?

I want to run simple go code directly from terminal/command line.我想直接从终端/命令行运行简单的 go 代码。 For example:例如:

go run "
package main
func main() {
println("hello")
}
"
hello

However golang allows code execution only from file.但是 golang 只允许从文件执行代码。 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.但是在上述操作之后应该没有文件。

In command-line, only a project like go-repl would compile/run a multi-line go source code without leaving any .go file behind.在命令行中,只有像go-repl这样的项目才能编译/运行多行 go 源代码,而不会留下任何.go文件。
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? ") (其他类似 repl 的解决方案在“ Go 是否提供 REPL? ”中列出)

Or you would need to develop a go wrapper which would internally create a source code and go run it, before deleting it.或者你需要开发一个 go 包装器,它会在内部创建一个源代码并在删除它之前运行它。

Ubuntu has a gorun tool which works well for small scripts. Ubuntu 有一个gorun工具,它适用于小脚本。 It compiles scripts on the fly, caching the binaries in /tmp.它动态编译脚本,将二进制文件缓存在 /tmp 中。

https://wiki.ubuntu.com/gorun https://wiki.ubuntu.com/gorun

Although it's intended for scripting and not as a REPL, you could use it in various ways.尽管它是用于编写脚本而不是用作 REPL,但您可以通过多种方式使用它。

Although gorun has come from the Ubuntu community, it should work on any Linux distro because it uses vanilla Go source code via尽管gorun来自 Ubuntu 社区,但它应该适用于任何 Linux 发行版,因为它通过以下方式使用 vanilla Go 源代码

$ go get launchpad.net/gorun

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM