如何在Golang中动态运行函数?

huangapple go评论89阅读模式
英文:

How to run function dynamically in golang?

问题

play.golang.org是一个在线的Go语言代码编辑器和运行环境。它的内部工作原理是将用户输入的Go代码进行编译和运行。

当你在play.golang.org上提交代码时,它会将代码发送到后台服务器进行处理。服务器会使用Go编译器将代码编译成可执行文件。然后,服务器会运行这个可执行文件,并将输出结果返回给你。

对于你提到的情况,如果你有一个函数作为字符串,并且需要检查语法并在golang的main函数中运行代码,你可以将这个字符串作为输入提交给play.golang.org。服务器会尝试编译和运行这段代码,并返回结果给你。你可以查看返回的结果来了解代码的运行情况。

英文:

How internally play.golang.org compiles and run the go code?

I have a function as string. I need to check the syntax and run the code inside golang main function.

答案1

得分: 4

代码被发送到服务器进行编译和执行,然后将输出发送回客户端(浏览器)。

有一篇关于它如何工作的文章:https://blog.golang.org/playground

英文:

The code is sent to a server to be compiled and executed then the output is sent back to the client (the browser).

There is an article on how it works : https://blog.golang.org/playground

答案2

得分: 1

Go代码在动态运行方面有些困难。你可以使用parser包来“检查”语法,尽管在go下使用这些包可能有些棘手。要实际运行它,你可能需要:

  1. 将函数保存到临时目录中,可能会生成一个main函数来调用它。
  2. 执行go编译器以生成可执行文件。
  3. 运行编译后的二进制文件,可能将标准输入和标准输出重定向到父进程。
  4. 通过标准输入/标准输出与其进行通信,直到它退出。

这显然是一个很麻烦的过程。

如果不一定需要使用Go,还有多种带有Go实现的脚本语言可供选择。如果你提供JavaScript、Lua或其他代码,可以动态运行它们。

英文:

Go code is a bit hard to run dynamically. You can "check" the syntax with the parser package, although using those packages under go can be a bit tricky. To actually run it, you would likely need to:

  1. Save the function to a temporary directory, possibly generating a main to invoke it.
  2. exec the go compiler to generate an executable
  3. Run the compiled binary, possibly piping stdin and stdout to the parent process.
  4. Communicate with it over stdin/stdout until it exits

This is obviously a big runaround and quite a pain.

If go is not strictly required there are multiple scripting languages with go implementations. If you supply javascript or lua or whatever code, you can run that dynamically.

huangapple
  • 本文由 发表于 2017年5月23日 23:30:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/44139161.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定