dongsimang4036 2015-02-28 15:51 采纳率: 100%
浏览 146
已采纳

如何使golang执行字符串

I am not asking to make golang do some sort of "eval" in the current context, just need it to take a input string (say, received from network) and execute it as a separate golang program.

In theory, when you run go run testme.go, it will read the content of testme.go into a string and parse, compile and execute it. Wonder if it is possible to call a go function to execute a string directly. Note that I have a requirement not to write the string into a file.

UPDATE1

I really want to find out if there is a function (in some go package) that serves as an entry point of go, in another word, I can call this function with a string as parameter, it will behave like go run testme.go, where testme.go has the content of that string.

  • 写回答

1条回答 默认 最新

  • doujiene2845 2015-02-28 16:28
    关注

    AFAIK it cannot be done, and the go compiler has to write intermediate files, so even if you use go run and not go build, files are created for the sake of running the code, they are just cleaned up if necessary. So you can't run a go program without touching the disk, even if you manage to somehow make the compiler take the source not from a file.

    For example, running strace on calling go run on a simple hello world program, shows among other things, the following lines:

    mkdir("/tmp/go-build167589894", 0700) 
    // ....
    mkdir("/tmp/go-build167589894/command-line-arguments/_obj/exe/", 0777) 
    // ... and at the end of things
    unlink("/tmp/go-build167589894/command-line-arguments/_obj/exe/foo") 
    // ^^^ my program was called foo.go
    // ....
    // and eventually:
    rmdir("/tmp/go-build167589894")
    

    So you can see that go run does a lot of disk writing behind the scenes, just cleans up afterwards.

    I suppose you can mount some tmpfs and build in it if you wish, but otherwise I don't believe it's possible.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3