Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 394
Timur Fayzrakhmanov Avatar asked Jan 03 '15 09:01

Timur Fayzrakhmanov


1 Answers

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.

like image 101
VonC Avatar answered Oct 02 '22 17:10

VonC