当前位置: > > > > 如何从用户输入以惰性方式初始化包的全局变量?
如何从用户输入以惰性方式初始化包的全局变量?
来源:stackoverflow
2024-04-24 12:57:28
0浏览
收藏
欢迎各位小伙伴来到米云,相聚于此都是缘哈哈哈!今天我给大家带来《如何从用户输入以惰性方式初始化包的全局变量?》,这篇文章主要讲到等等知识,如果你对Golang相关的知识非常感兴趣或者正在自学,都可以关注我,我会持续更新相关文章!当然,有什么建议也欢迎在评论留言提出!一起学习!
问题内容
我的项目中有多个包:主要包和次要包。主要部分接受用户的输入并初始化一些变量。 辅助包包含一些全局变量,这些变量只能在“主”包初始化后才能初始化,而不能更早。
我知道包的函数“init()”,但这在我的情况下不起作用,因为它无法以惰性方式初始化数据,并且无法使用来自外部的一些参数或数据。而这正是我想要的。
//main package
var (
a1 int
a2 float
a3 string
a4 MyStruct
a5 MyStruct2
)
func main() {
//process user input
//...........
//some other stuff
// I want that by this point, the global variables of package2 to have been initialized
// **based on** the processed user input from above
//namely, before the first access to the package
package2.Func1()
// I want that by this point, the global variables of package3 to have been initialized
// **based on** the processed user input from above
//namely, before the first access to the package
package3.Func11()
}
这个问题有解决办法吗?
我可以在包 package2 和 package3 中有一个函数“initdata()”,但是我如何确保在调用任何函数之前不会忘记以强制方式将其作为第一个函数调用包的其他功能?
正确答案
你应该在 main.go 中使用 init 函数
func init(){
// get user input and set variables
// call package 2 and 3 after setting the variables in main
package2.Func1()
package3.Func1()
}
func main(){
// everything is setup properly when code in this main function is launched
}
好了,本文到此结束,带大家了解了《如何从用户输入以惰性方式初始化包的全局变量?》,希望本文对你有所帮助!关注米云公众号,给大家分享更多Golang知识!
