"no stuttering" vs embedded types

xuanbao · · 495 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>Effective Go and golint encourage you to avoid &#34;stuttering&#34; by giving names like <code>json.Formatter</code> instead of <code>json.JSONFormatter</code>; for example, most Reader types are just named <code>Reader</code>, &#34;because users see it as <code>bufio.Reader</code>&#34;.</p> <p>I generally like this approach... but it seems to fall apart with struct embedding. Embedded struct names are just the type name without package, and I find it makes it much harder to read initializers (especially). It&#39;s almost enough to make me want to entirely avoid the &#34;no stuttering&#34; guideline for types that I embed in other packages in my projects. Any thoughts on this?</p> <hr/>**评论:**<br/><br/>chownplus: <pre><p>Even within the stdlib there&#39;s stuttering, &#34;io/ioutils&#34; being one of the big ones. It&#39;s just a guideline.</p></pre>tdewolff: <pre><p>What do you mean with struct embedding?</p> <p>I&#39;ve seen instances in the stdlib where there is stuttering because any other name would not make sense. For example, I have a <code>minify</code> package containing a <code>Minifier</code> struct which can <code>Minify(...)</code>. Sometimes it&#39;s just that, but can you give an example of your struct naming?</p></pre>Brasilikum: <pre><p>He means something like</p> <p><code> struct App{ logrus.Logger Other Fields } app := App{Logger: logrus.New()} </code></p> <p>My thought on this is while this does not make it that obvious, I don&#39;t see a pragmatic alternative. I find it good enough that I am warned if I am trying to put in the wrong type. </p></pre>jerf: <pre><p>I have definitely on occasion wished I could both embed and name a field. As near as I can see there&#39;s no particular reason that shouldn&#39;t be possible. (I&#39;m comfortable with it being a compile-time error if I try to embed two of the same type, which it already is, so no change there.)</p></pre>izuriel: <pre><p>To avoid confusion with this I try to only embed interface types. This way anything conforming to the interface will fit, and if not a simple wrapper around whatever I want that doesn&#39;t conform will make it fit the bill and it&#39;s done. Then naming of embedded types isn&#39;t really a concern.</p></pre>

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

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