doulang1945 2014-10-02 22:07
浏览 34
已采纳

在Go中存储状态

I'm writing a simple program in Go as an exercise to learn the language. The program is a game player: it exec.Commands a text-based game, then communicates with it via StdinPipe/StdoutPipe. After some fooling around and reading a lot of online docs I managed to get the skeleton working -- the equivalent of Hello World, where I've established two-way communication and can handle errors like the program terminating.

Now I'm trying to write the actual game-playing AI code. Since my purpose is learning the language, I'm trying to be very careful with style -- I don't just want to write C (or some other language) in Go.

The obvious division of labor in the program (once all the setup is done) is into two parts. First, the program looks at the current state and decides what command should be issued to the game. Second, the program looks at the data returned and updates the state accordingly. (Yes, it's a simple game -- it waits for input and then responds, there are no timing issues.)

I'm not sure where this state information should go. Dumping it all into the global scope feels wrong, and making a massive singleton object seems even worse (and Go isn't particularly OO). In any case I don't want to have the functions pass and return 20+ variables.

General advice is fine, but I'm most interested in what is idiomatically appropriate for Go. On request I can share code but I don't think it would be helpful.

  • 写回答

2条回答 默认 最新

  • dreamlife2014 2014-10-02 22:22
    关注

    Go does enable a style of OO programming.

    Create a struct type for the game state. Pass a pointer to a value of this type around in your program or store the pointer in a package level variable if that sort of thing does not bother you. Implement methods on this type as needed. Consider putting it in its own package for greater encapsulation.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度