<p>Will someone help me out. I'm learning go through "go a thorough introduction". I'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 "[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 :=" "
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 ""
}
</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("[%v:%v]", 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't realize that I could use range for array - however, it's putting the string together in one return statement that's really getting me confused. But after resting my eyes for a few I'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
0 回复
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传