英文:
How to reduce number of parameters in go nested function calls
问题
我有一个按照以下结构组织的go Calltree:
// state是一个在所有"MyType"实例之间共享的常见结构体,模拟接口的成员变量
(s MyType) Run(state *State){ // 从外部调用
// 定义通过http获取数据的goroutines
HTTPCallback(){ // 在每个http响应中运行
parseData(record, outputChan)
}
}
(s MyType) parseData(rec []string, outputChan chan(interface{})){
// 目前不需要从"state"获取任何东西
doIdMapping(string)
}
doIdMapping(key) {
return state.Map[key]
}
有没有一种方法可以在不被迫通过HTTPCallback和上面的所有goroutines传递"state"的情况下访问Map(完全是常量)?
这不仅对于清晰的代码来说是不好的,而且在测试时也是不好的。所有中间函数都携带着它们甚至不需要依赖的结构体指针。我是否错过了关于go语言设计的一些东西? :/
英文:
I have a go Calltree which is structured as follows:
// 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]
}
Is there a way of getting access to the Map (which is completely constant) without being forced to pass the "state" through HTTPCallback and all the goroutines above which end up in calling HTTPCallback?
This is not only bad for a clear code but also is bad when it comes to testing. All the intermediate functions carry around that struct pointer which they don't even need to depend on. Did I miss something about the language design of go? :/
答案1
得分: 2
如果所有这些内容都在一个包内,你可以在包级别上声明State
并在任何地方使用它。例如:
package myHttpClient
import (
"allthatstuff"
)
var state State // 在'myHttpClient'中无需导出,但可在任何地方使用
var ExternState State // 导出的,所以任何导入'myHttpClient'的人都可以使用myHttpClient.ExternState
希望对你有帮助!
英文:
If all of this is within a single package you can simply declare State
at the package level and use it everywhere. For example;
package myHttpClient
import (
"allthatstuff"
)
state State // not exported but available everywhere in 'myHttpClient'
ExternState State // exported so anyone importing myHttpClient can do myHttpClient.ExternState
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论