<p>I've Googled all over for this on several occasions, and it appears no one has asked this question publicly before. Is it possible to loop over a non-builtin type with templates? For example, can I iterate over a <code>bufio.Scanner</code>? Or is it necessary to use an intermediate slice or channel? I suspect it's not possible, but asking seems useful if only for posterity.</p>
<hr/>**评论:**<br/><br/>balloonanimalfarm: <pre><p><a href="https://golang.org/pkg/text/template/" rel="nofollow">godoc specifies</a> that the parameter for <code>template</code>'s range function "...must be an array, slice, map, or channel."</p>
<p>You might be able to "hack" it using pipelines dynamically wrapping your type, but then you're probably better off just writing an iterator that outputs on a channel to begin with.</p></pre>weberc2: <pre><p>Yeah, that's what I figured. Thanks for the info.</p></pre>natefinch: <pre><p>the template stuff is written under the assumption that you have all the data in hand, not that you're gathering it while you're writing the template. Not sure of your use case, but would it be the end of the world to loop over the scanner and stash the results in a slice?</p></pre>weberc2: <pre><blockquote>
<p>the template stuff is written under the assumption that you have all the data in hand, not that you're gathering it while you're writing the template</p>
</blockquote>
<p>Range works on channels, which seems to indicate that there <em>is</em> a legitimate use case for iterative template execution.</p>
<blockquote>
<p>Not sure of your use case, but would it be the end of the world to loop over the scanner and stash the results in a slice?</p>
</blockquote>
<p>Of course not. :) The alternatives are obvious and not too difficult; I just wanted to make sure I wasn't missing something, and also leave a bit of documentation behind for posterity.</p></pre>mc_hammerd: <pre><p>typically you do a channel and iterate over that (probably what bufio.scanner is)</p></pre>weberc2: <pre><p>I'm not sure how bufio.Scanner is implemented, but it would be nice to use its interface rather than wrapping it in a goroutine that dumps data into a channel. It's not a bad workaround, but it's not as straightforward as a simple for loop. Oh well.</p></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传