14

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.

Timur Fayzrakhmanov
  • 17,967
  • 20
  • 64
  • 95

2 Answers2

7

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.

Community
  • 1
  • 1
VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250
1

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
Rick-777
  • 9,714
  • 5
  • 34
  • 50
  • `go: missing Bazaar command` the above command throws me an error – muthukumar selvaraj Jan 30 '18 at 07:36
  • @muthukumarhelius You need to install the Bazaar version tool as Ubuntu hosts their gorun-code in a bzr repo. See more here: https://github.com/golang/go/wiki/GoGetTools – nover Feb 20 '20 at 19:04