<p>Well, I couldn't solve this one beautifully, so I wanted to see how better gophers would solve it</p>
<p>consider the following slice:</p>
<pre><code>[]string{"one", "two" `"three`, "four", `five"`}
</code></pre>
<p>convert that to the following:</p>
<pre><code>[]string{"one", "two", "three four five"}
</code></pre>
<hr/>
<p>other examples:</p>
<p><strong>IN</strong></p>
<pre><code>[]string{`"one`, `two"`, "three"}
</code></pre>
<p><strong>OUT</strong></p>
<pre><code>[]string{"one two", "three"}
</code></pre>
<hr/>
<p><strong>IN</strong></p>
<pre><code>[]string{"one", `"two"`}
</code></pre>
<p><strong>OUT</strong></p>
<pre><code>[]string{"one", "two"}
</code></pre>
<hr/>
<p><strong>IN</strong></p>
<pre><code>[]string{"one", `"two`, "three", "four", "five", `six"`}
</code></pre>
<p><strong>OUT</strong></p>
<pre><code>[]string{"one", "two three four five six"}
</code></pre>
<p>you get the idea.</p>
<hr/>**评论:**<br/><br/>jasonmoo: <pre><p><a href="http://play.golang.org/p/BWtiiPJ1M3">http://play.golang.org/p/BWtiiPJ1M3</a></p></pre>pyThat: <pre><p>great solution, you win !</p></pre>srtkkou: <pre><p>How about something like this?
<a href="https://play.golang.org/p/TzB-qochQM">https://play.golang.org/p/TzB-qochQM</a></p></pre>pyThat: <pre><p>Kudos for that solution, you still lose a point tho for allocating a new slice</p></pre>daveddev: <pre><p>I am not a clever man. <a href="http://play.golang.org/p/wTrNtFdnmI" rel="nofollow">http://play.golang.org/p/wTrNtFdnmI</a></p></pre>daveddev: <pre><p>Ah, hahah. The backticks went right over my head. I'll try again when I get a moment.</p></pre>daveddev: <pre><p>This is what I believe to be a good balance between speed, reduced allocations, and maintainability. <a href="http://play.golang.org/p/hjDV7KZ9HH" rel="nofollow">http://play.golang.org/p/hjDV7KZ9HH</a></p></pre>djherbis: <pre><p>I don't know if I would call this clever, but it's fairly short :P</p>
<p><a href="https://play.golang.org/p/DZlkOFb4-X" rel="nofollow">https://play.golang.org/p/DZlkOFb4-X</a></p>
<p>(one slightly clever part is that the returned slice is actually the original slice, just modified, and it'll never grow that slice, this might not be considered clever if you don't like that it is "destructive" but that could easily be fixed with a copy).</p></pre>pyThat: <pre><p>it is clever that you used the same slice, but it is fairly complicated to follow.
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传