Templates: Looping over custom type?

xuanbao · · 485 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>I&#39;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&#39;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>&#39;s range function &#34;...must be an array, slice, map, or channel.&#34;</p> <p>You might be able to &#34;hack&#34; it using pipelines dynamically wrapping your type, but then you&#39;re probably better off just writing an iterator that outputs on a channel to begin with.</p></pre>weberc2: <pre><p>Yeah, that&#39;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&#39;re gathering it while you&#39;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&#39;re gathering it while you&#39;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&#39;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&#39;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&#39;s not a bad workaround, but it&#39;s not as straightforward as a simple for loop. Oh well.</p></pre>

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

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