如何减少嵌套函数调用中的参数数量

时间:2015-07-22 16:38:27

标签: go

我有一个Calltree,其结构如下:

// state is a common struct shared among all "instances" of MyType - simulating member variables for an Interface
(s MyType) Run(state *State){ // called from outside
  // define goroutines that fetch something via http
  HTTPCallback(){ // runs on every http response
    parseData(record, outputChan)
  }
}
(s MyType) parseData(rec []string, outputChan chan(interface{})){
  // doesn't need anything from "state" so far
  doIdMapping(string) 
}


doIdMapping(key) { 
   return state.Map[key] 
}

有没有办法访问Map(这是完全不变的)没有被强制通过HTTPCallback传递“状态”以及上面最终调用HTTPCallback的所有goroutine? / p>

这不仅对于清晰的代码有害,而且在测试方面也很糟糕。所有中间函数都带有它们甚至不需要依赖的结构指针。我是否想念一下go的语言设计? :/

1 个答案:

答案 0 :(得分:2)

如果所有这些都在一个软件包中,您只需在软件包级别声明State并在任何地方使用它。例如;

package myHttpClient

import (
    "allthatstuff"
)

state State // not exported but available everywhere in 'myHttpClient'
ExternState State // exported so anyone importing myHttpClient can do myHttpClient.ExternState