<p>I can't find any information on this that's explicit.</p>
<p>Let's say you have a package called "apiWrapper" and in it you have a global struct called "Config" that gets set by "init()". "Config" has a string field called "ApiKey" and is initially set to "none".</p>
<p>Now in a separate package, let's call it package "Foo", you have file A.go and file B.go each include package "apiWrapper". In A.go, it sets "apiWrapper.Config.ApiKey = "xyz"" and in B.go, it reads "apiWrapper.Config.ApiKey" for whatever reason. If A.go is executed first, would B.go read it as "none" or "xyz"?</p>
<p>And also, how about instead of being files, A and B are subpackages to Foo, would B still read it as "none" or "xyz"?</p>
<p>I guess the real question at hand is, per executable, when you include a package in multiple locations, is it one "entity" (for lack of a better term) that everywhere references or does each location get its own "copy" of that package?</p>
<hr/>**评论:**<br/><br/>cs-guy: <pre><p>From <a href="http://golang.org/ref/spec#Package_initialization">the language spec</a>:</p>
<blockquote>
<p>If a package has imports, the imported packages are initialized before initializing the package itself. If multiple packages import a package, the imported package will be initialized only once.</p>
</blockquote></pre>klaaax: <pre><p>init is executed only once. Try to avoid globals as much as possible anyway, I never found a good case for init. Maybe someone can come up with one.</p></pre>mwholt: <pre><p>I use init to initialize an unexported <code>map[string]func()</code> where the (relatively simple) functions in the map call functions that end up calling other functions in the map. Doing this outside of init creates an initialization loop error.</p>
<p><code>init()</code> is also nice for using the flag package outside the flow of your <code>main()</code> so you can keep it clean.</p></pre>petejodo: <pre><p>yeah you're right, it was just an easy way to express my question which revolved more around how packages worked. I somehow never came across the section of the language spec that cs-guy posted above so my mental model of packages has been shaky at best</p></pre>Azzk1kr: <pre><p><a href="https://github.com/surma/stacksignal" rel="nofollow">This stacksignal</a> package was one interesting thing which makes use of init(). Just import the package, and you'll get a signal handler on SIGUSR1.</p></pre>DavidDavidsonsGhost: <pre><p>Its nice and useful to use init to add modules or plugins to other module must by importing the plugin in your main. If you look at the image decoders in the standard library you will see an example of this.</p></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传