interface{} question

polaris · · 358 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>hey folks newbie question here but in the code <a href="https://play.golang.org/p/5CNdVb1DXL" rel="nofollow">https://play.golang.org/p/5CNdVb1DXL</a> since Cache is an interface and MemoryCache is an implementation of that why can I not assign &#34;TheCache = NewMemoryCache()&#34; and how should I go about that - thank you!!!</p> <hr/>**评论:**<br/><br/>sharptierce: <pre><p>There are two ways here: <a href="https://play.golang.org/p/n6O6V5lzu-" rel="nofollow">https://play.golang.org/p/n6O6V5lzu-</a> since Get only reads the pointer is not necessary.</p> <p>The other solution would be: <a href="https://play.golang.org/p/Owg-U_JYsk" rel="nofollow">https://play.golang.org/p/Owg-U_JYsk</a> where you take the pointer to the object and now it implements the interface.</p> <p>Kinda hard at the beginning to grasp :) </p></pre>runyoucleverboyrun: <pre><p>So how come there&#39;s a type problem when assigning a MemoryCache value to a Cache variable but not when assigning a MemoryCache pointer, and is the TheCache variable implicitly a pointer type or something?</p></pre>driusan: <pre><p>There&#39;s a type error when assigning a MemoryCache value because you didn&#39;t implement the interface on type MemoryCache, you implemented it on type *MemoryCache.</p></pre>sharptierce: <pre><p>if you define methods that have a pointer receiver they will only be implemented by pointers of the instance. Methods that have no pointe r receiver are implemented by both. </p> <p>Methods with pointer receiver can manipulate the struct.</p> <p>I&#39;m bad at explaining though, you can read it up here <a href="https://golang.org/doc/faq#pointer_to_interface" rel="nofollow">https://golang.org/doc/faq#pointer_to_interface</a></p></pre>pafortin: <pre><p>thank you that was very helpful and got me unstuck!</p></pre>binaryblade: <pre><p>Inorder for a value to satisfy an interface it must be a pointer if one of the method receivers required by the interface is a pointer. Its safe to automatically reduce to a value but not to take a pointer.</p></pre>

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

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