Strin() method help

blov · · 360 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>Will someone help me out. I&#39;m learning go through &#34;go a thorough introduction&#34;. I&#39;m stuck on an exercise which I have to implement a String() method on a structure which contains an array of integers. The purpose is to print the contents of the array in this format &#34;[0:value] [1:value]...etc</p> <p>Will someone point me in the correct direction? Thanks.</p> <p>Thanks for everyones help :</p> <p>tmp-str :=&#34; &#34; For k, v := range stack { tmp-str += // concatenate literals plus returns from strconv.Itoa} return tmp-str</p> <hr/>**评论:**<br/><br/>drunken_thor: <pre><p>Well show me what you got so far? you at least need </p> <pre><code>func (mystruct Mystruct) String() string { return &#34;&#34; } </code></pre> <p>Then you also need those values with their indexes let say something like</p> <pre><code>for i, val := range arr { // use index and val for your strings: [1:value] } </code></pre> <p>Then maybe you could put them into a string together like this</p> <pre><code>fmt.Sprintf(&#34;[%v:%v]&#34;, i, val) </code></pre> <p>Then try and put it together using the <code>strings</code> package somehow. :D I did most of it for you. Take it the next step!</p></pre>ops_man: <pre><p>Thanks. I feel stupid. I didn&#39;t realize that I could use range for array - however, it&#39;s putting the string together in one return statement that&#39;s really getting me confused. But after resting my eyes for a few I&#39;m going to tackle again with your suggestion. Thank you. </p></pre>drunken_thor: <pre><p>I always found this method helpful <a href="https://golang.org/pkg/strings/#Join" rel="nofollow">https://golang.org/pkg/strings/#Join</a></p></pre>SteveMcQwark: <pre><p>A fairly common solution is <a href="https://golang.org/pkg/bytes/#Buffer.WriteString" rel="nofollow">https://golang.org/pkg/bytes/#Buffer.WriteString</a></p></pre>

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

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