doutan6286 2015-11-04 22:00 采纳率: 100%
浏览 43
已采纳

如何全局定义结构并重用其包

Im very new to Go and have this "design" problem.

I have a main program passing jobs through channels. Each job will end up in a function defined in separate "worker" packages. Jobs are structs.

Now i want each function called, to return result as a common struct through a "result" channel. But the package doesnt know about the struct definition i have in main and so i cannot define it.

package main

type resultEvent struct {
    name  string
    desc  string
}

Then in a worker package:

package worker

func Test() {
   result := &resultEvent{name: "test"}
}    

Of course the idea is to eventually send this result down a channel, but even this simple example wont work, because worker doesnt know about resultEvent. What would be the correct way of doing this?

Update:

It should be noted that there will be many worker packages, doing different things. Sorta like "plugins" (only not pluggable at all). I dont want to define a redundant struct in each go-file and then have to maintain that over maybe 50 very different worker-packages.

Im looking for what would be the correct way to structure this, so i can reuse one struct for all worker-packages.

  • 写回答

3条回答 默认 最新

  • ds2128629 2015-11-05 09:08
    关注

    One possible way would be something like:

    package workerlib
    
    type ResultEvent struct {
      Name        string  // Export the struct fields, unless you have a
      Description string  // real good reason not to.
    }
    

    Then stick the rest of the worker utility functions in that package. Unless you provide suitable methods to read the name and description from an event, simply export the fields. If you have an absolute need to make them changeable only from within the package they're defined in, you could keep them unexported, then provide a function to create a ResultEvent as well as methods to read the name and description.

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

报告相同问题?

悬赏问题

  • ¥15 CSS实现渐隐虚线框
  • ¥15 有没有帮写代码做实验仿真的
  • ¥30 vmware exsi重置后登不上
  • ¥15 易盾点选的cb参数怎么解啊
  • ¥15 MATLAB运行显示错误,如何解决?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?
  • ¥15 电磁场的matlab仿真