What does this mean? Basic Go

agolangf · · 395 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>Hi,</p> <p>I&#39;m looking for some info on what the following does:</p> <p>itemresp := &amp;api.RetrieveResponse{}</p> <p>I&#39;d like to create a new (faked) value and assign it to RetrieveResponse. How would I go about it, if the type definition for RetrieveResponse is as follows:</p> <p>type RetrieveResponse struct { Status int Complete int List map[string]Item Since int }</p> <hr/>**评论:**<br/><br/>v0idl0gic: <pre><p>itemresp := &amp;api.RetrieveResponse{} </p> <p>is the same as:</p> <p>itemresp := new(api.RetrieveResponse) </p></pre>TUSF: <pre><p>You want to look up struct literals. <a href="https://tour.golang.org/moretypes/5" rel="nofollow">https://tour.golang.org/moretypes/5</a></p> <p>Here&#39;s an example of what you might do:</p> <pre><code>itemresp := &amp;api.RetrieveResponse{ 200, 2000, map[string]Item{ &#34;firstItem&#34;: Item{} }, 1458676981 } </code></pre> <p>If you want a bit more control (such as excluding some parameters):</p> <pre><code>itemresp := &amp;api.RetrieveResponse{ Status: 200, Complete: 2000, Since: 1458676981 } </code></pre></pre>ahfeck1t: <pre><blockquote> <p>itemresp := &amp;api.RetrieveResponse{ Status: 200, Complete: 2000, Since: 1458676981 }</p> </blockquote> <p>Thanks!</p></pre>qcoh: <pre><blockquote> <p><code>itemresp := &amp;api.RetrieveResponse{}</code> </p> </blockquote> <p>From the spec:</p> <blockquote> <p>Taking the address of a composite literal generates a pointer to a unique variable initialized with the literal&#39;s value.</p> </blockquote> <p>Not sure if I parse the rest of your question correctly. Do you want to create an object of type <code>*api.RetrieveResponse</code> with fake (?) values? Try <code>itemresp := &amp;api.RetrieveResponse{Status: 123, Complete: 456, List: make(map[string]Item), Since: 789}</code>.</p></pre>ahfeck1t: <pre><p>Will give it a go - thats a great reference on the composite literal. Havent come across that syntax to date, and that explains it very well. Thanks</p></pre>

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

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