Why I can in go return in a function a struct that is private, what is the use case of this?

xuanbao · · 438 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>a code example could be like</p> <p>package demo</p> <p>type priv struct{}</p> <p>func Demo() priv{ return priv{} }</p> <hr/>**评论:**<br/><br/>binaryblade: <pre><p>That unexported type could satisfy a visible interface.</p></pre>TheMerovius: <pre><p>See <a href="https://godoc.org/encoding/binary#pkg-variables" rel="nofollow">encoding/binary</a> for an example of how exposing unexported types can be useful.</p></pre>mrkaspa: <pre><p>Thanks!</p></pre>materialdesigner: <pre><p>Because nothing in go is &#34;private&#34;/&#34;public&#34;, it&#39;s &#34;unexported&#34;/&#34;exported&#34;. It might seem like an unimportant difference but this is exactly why. </p> <p>What is the use case? One use case is to only expose a Smart Constructor that doesn&#39;t let you create a struct with meaningless or uninitialized values. But it is frowned upon by tools like golint</p></pre>dilap: <pre><p>Not that useful though, because in the calling package you can&#39;t write down the type, meaning you can only use the result within a single functions scope:</p> <p>x := p.Demo() // returns a private type</p> <p>I don&#39;t see it so much as &#34;why does it allow&#34; but more &#34;no reason to disallow&#34;.</p></pre>RalphCorderoy: <pre><p>Do you mean <code>func demo</code> to have a capital D?</p></pre>mrkaspa: <pre><p>Yes sorry, I updated it</p></pre>THEHIPP0: <pre><p>You can use this function from within the package from another function. Also the function is private too.</p></pre>dlsniper: <pre><p>Demo() is exported from package demo since it starts with a capital letter.</p></pre>

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

438 次点击  
加入收藏 微博
0 回复
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传