<p>Here's a relatively smaller code. This is part of parsing a <code>yaml file</code>. This code to define structure to parse a yaml file. It works but I would like to know why!</p>
<pre><code>type GLBConfig struct {
GLBs []GLBList `json:"glb_list" yaml:"glb_list"`
}
type GLBList struct {
Failover string `json:"failover" yaml:"failover"`
GLB string `json:"glb" yaml:"glb"`
Pool []struct {
Fqdn string `json:"fqdn" yaml:"fqdn"`
PercentConsidered int `json:"percent_considered" yaml:"percent_considered"`
} `json:"pool" yaml:"pool"`
}
</code></pre>
<p>The confusion is that, I've used <code>GLBList</code> in the struct <code>GLBConfig</code> even before defining it? Doesn't order of defining matter?</p>
<p>Thanks</p>
<hr/>**评论:**<br/><br/>drvd: <pre><p>No.</p></pre>neonsteven: <pre><p>Well put. Let me try to expand a bit :).</p>
<p>The <a href="https://golang.org/ref/spec#Declarations_and_scope">language spec</a> answers the question in a fairly technical way.</p>
<blockquote>
<p>The scope of an identifier denoting a constant, type, variable, or function (but not method) declared at top level (outside any function) is the package block.</p>
</blockquote>
<p>In other words, when you say "type foo struct {}" then "foo" is defined everywhere in the package, including earlier in the same file and in other files.</p></pre>shadyabhi: <pre><p>Thanks! That was helpful. Appreciate the spec reference.</p></pre>kpmy: <pre><p>This is kind of automatic "forward declaration" feature.</p></pre>shadyabhi: <pre><p>As per FAQ, golang doesn't have forward declaration. <a href="https://golang.org/doc/faq" rel="nofollow">https://golang.org/doc/faq</a></p></pre>bmurphy1976: <pre><p>This is why: <a href="https://en.wikipedia.org/wiki/Multi-pass_compiler" rel="nofollow">https://en.wikipedia.org/wiki/Multi-pass_compiler</a></p></pre>natefinch: <pre><p><a href="http://static.guim.co.uk/sys-images/Money/Pix/pictures/2013/11/14/1384434812854/Milla-Jovovich-with-her-M-008.jpg" rel="nofollow">multipass</a></p></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
0 回复
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传