Shadowing packages with variables?

polaris · · 473 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>Lots of packages in the standard library use names that I often want to use for variables. For example: <code>net/url</code>, <code>path</code>, <code>encoding/json</code>, etc ... I&#39;ve always went out of my way to give my variables names that didn&#39;t shadow package names but then I noticed that the stdlib doesn&#39;t care about it <a href="https://godoc.org/net/http#Get">https://godoc.org/net/http#Get</a> . </p> <p>What&#39;s your opinion?</p> <hr/>**评论:**<br/><br/>Sphax: <pre><p>In my experience it doesn&#39;t come up much. Thinking about it the most problematic is net/url, and then I just use u or something.</p></pre>danredux: <pre><p>Yeah it basically never comes up.. There&#39;s two ways the conflict could happen. </p> <p>Way 1: You have imported the package previously and are now in a function declaring a variable of the same name. This is only problematic if you also want to use that package more than twice in this function scope.</p> <p>Way 2: You are in an existing function and now want to import a package whose name conflicts with a variable in that functions scope. This isn&#39;t problematic as that function definitely isn&#39;t using that package yet, so there&#39;s no real conflict until way 1 occurs.</p> <p>So yeah, it barely happens, and it only happens to function-scoped variables of which I rarely have more than a few and they rarely show up in more than a few lines.</p></pre>kkirsche: <pre><p>I generally try to avoid shadowing packages. While you can do it, I&#39;ve found it easier when I return a month or two later to quickly parse the file. Admittedly though, I think it is dependent on what the functions are though as to how much this would or wouldn&#39;t hold true for you</p></pre>barsonme: <pre><p>Stdlib usually does stuff like <code>urlStr</code> instead of <code>url</code></p> <p>Kinda sucks but shadowing can get annoying and then you&#39;ll have to go back and rename variables, which even with an IDE isn&#39;t fun. </p></pre>SingularityNow: <pre><p>Sounds like you should check out gorename if you think renaming variables is a pain.</p></pre>icholy: <pre><p>In the url package, it&#39;s called rawurl.</p></pre>

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

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