<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 "private"/"public", it's "unexported"/"exported". 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'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'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't see it so much as "why does it allow" but more "no reason to disallow".</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>
Why I can in go return in a function a struct that is private, what is the use case of this?
xuanbao · · 438 次点击这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传