Embedding a struct, override a new field?

blov · · 969 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>Hello again all.</p> <p>Thanks for your help on prior questions as I move from super heavy OOP languages to Golang.</p> <p>Suppose in package &#39;a&#39;, I have:</p> <pre><code>type Config struct { path string `json:&#34;-&#34;` } </code></pre> <p>Then in package &#39;b&#39;, I have:</p> <pre><code>type localConfig struct { path string `json:&#34;-&#34;` Server remote.Server a.Config } </code></pre> <p>I know that when I embed, the methods act on the inner type/the one they&#39;re actually bound to. But in those methods, I need to reference &#39;path&#39;. If I create a new variable of &#39;localConfig&#39; and set the path in the composite literal, the methods see path as being empty (since it&#39;s using a.Config.path rather than b.localConfig.path). What&#39;s the easiest way to solve this in Golang? Do I just create a config interface that looks for a method that returns the path? That sounds messy :(</p> <p>Thanks!</p> <hr/>**评论:**<br/><br/>Ainar-G: <pre><p>Why don&#39;t you just use the <code>path</code> that&#39;s inside <code>a.Config</code>?</p></pre>trinchan: <pre><p>I&#39;m not sure about your use case as well, but you can reference the embedded Config path using localConfig.Config.path and the localConfig path using localConfig.path</p> <p>Working example <a href="http://play.golang.org/p/ZZQ4Nu8ri7" rel="nofollow">here</a>.</p></pre>JakeTheDev: <pre><p>... I can&#39;t believe I didn&#39;t think of this. Guess i&#39;m still stuck in the inheritance mindset. Thanks!</p></pre>klaaax: <pre><p>You want to use path in both structs then export path with an upper case.</p></pre>

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

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