why slice of raw type, e.g., byte is not supported as map keys but array of raw types is ok.

xuanbao · · 169 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>I read this article: . it says</p> <p>Key types</p> <blockquote> <p>As mentioned earlier, map keys may be of any type that is comparable. The language spec defines this precisely, but in short, comparable types are boolean, numeric, string, pointer, channel, and interface types, and structs or arrays that contain only those types. Notably absent from the list are slices, maps, and functions; these types cannot be compared using ==, and may not be used as map keys.</p> </blockquote> <hr/>**评论:**<br/><br/>gxti: <pre><p>Slices can&#39;t be used with == because they are a form of indirection and in Go == never does a deep comparison, hence why type-specific functions like <code>bytes.Equal</code> are used. The slice itself is just a pointer with a length and capacity, so in theory == would test whether two slices point to the same place which is almost completely useless but would definitely mislead beginners into thinking it is testing whether the <em>contents</em> are equal. Making it a syntax error avoids confusion.</p> <p>On the other hand, pointers channels and interfaces can be compared with == because, while it&#39;s still not doing any deep comparisons, it is less likely to mislead people. It&#39;s also sometimes useful to use pointers and channels as a map key, for example tracking clients that connect and disconnect from a server. On the other hand, I can&#39;t think of a good reason to do a shallow comparison of two slices.</p></pre>TinyBirdperson: <pre><p>&#34;form of indirection&#34; &#34;go never does a deep comparison&#34; &#34;just a pointer with a length&#34; strings. </p></pre>TheMerovius: <pre><p>Strings might be <em>implemented</em> as a pointer with a length, but that&#39;s not what they semantically are. There is no way (except using <code>unsafe</code>) to determine whether two strings are reference-equal or value-equal, but there is for slices:</p> <pre><code>len(a) == len(b) &amp;&amp; cap(a) == cap(b) &amp;&amp; (len(a) == 0 || &amp;a[0] == &amp;b[0]) </code></pre> <p>The compiler is entirely free to put any set of strings into the same memory area or different memory areas, however it pleases.</p></pre>nsd433: <pre><p>Because apart from 0-capacity slices the contents (elements) of a slice are mutable, and mutating them when they were in the map would make a mess.</p></pre>marksteve4: <pre><p>This is not true as struct with primitive types are also valid map key. you can still modify the struct</p></pre>

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

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