Is it possible to run Go code as a script?

后端 未结 5 2043
梦如初夏
梦如初夏 2021-02-05 17:21

As Go is becoming the language of the \"system\". I wonder if it\'s possible to run Go code as a script, without compiling it, is there any possibility to do that?

The

5条回答
  •  执念已碎
    2021-02-05 17:37

    As others noted, Go is a compiled language. Programs written in the Go language rely on the Go runtime which is added to the executable binary.

    The Go runtime provides certain vital features such as garbage collection, goroutine scheduling, runtime reflection etc. Without them a Go app cannot work as guaranteed by the language spec.

    A theoretical Go interpreter would have to simulate those features, which would essentially mean to include a Go runtime and a Go compiler. There is no such thing, and there is no need for that.
    Also note that if the code is not yet compiled, that means the Go interpreter would have to contain all the standard library, because a Go "script" could legally refer to anything from the standard library (when a Go app is compiled, only things that it uses / refers to gets compiled into the executable binary).

    To quickly test something, just use go run, which also compiles your app and builds an executable binary in a temporary folder, launches that temp file and cleans it when your app exits.

    "Solutions" posted by others may "feel" like scripting, but they are nothing more than automating / hiding the process of compiling the Go source to an executable binary and then launching that binary. This is exactly what go run does (which also cleans up the temporary binary).

提交回复
热议问题