How to run go code dynamically from string?-ThrowExceptions

Exception or error:

I need to execute code dynamically, for example to run fmt.Print("hello") (in string format), maybe what I am looking for is a go virtual machine?

With go-playground, we can type the code and execute it, how does that work behind?

The worst solution would be to write string code to a file and call it with exec.Command("go", "run","file").

How to solve:

1. Playground

With go-playground, we can type the code and execute it, how does that work behind?

I suppose that you answered your owm question in most part.

It does not take long to find source of compileAndRun from playground.

The worst solution would be to write string code to a file and call it with exec.Command(“go”, “run”,”file”).

And yes, it uses:
https://github.com/golang/playground/blob/509e10fc018f6da63e433d45afbf5c21af9480a2/sandbox.go#L361

    cmd := exec.Command("go", "build", "-o", exe, buildPkgArg)

2. Jupyter kernels, gore, lgo, gophernotes and gomacro

Although it does not means that it must be always this way.

I myself plan to look in spare time into:

  • gophernotes
  • lgo
  • and gomacro which itself is package used for gophernotes

Overall: it’s not that easy as eval in other languages but nothing stops to implement it.

Good luck!

Leave a Reply

Your email address will not be published. Required fields are marked *