<p>Since io.Reader is the idiomatic way for reading in data in Go. Does anyone know why text/template does not have a function taking in io.Reader? I know it is fairly simple to create a wrapper, I just find it odd that it's not there.</p>
<hr/>**评论:**<br/><br/>kylewolfe: <pre><p>Think about why io.Reader is used in most cases, and not just because it's idiomatic. The json package for example, does not need to read the entire byte slice in to memory in order to parse it. It utilizes a tokenizer. This means that io.Reader is acting like a pointer to the original slice of bytes, preventing unnecessary memory usage.</p>
<p>text/template however, needs an entire copy of the byte slice in order to do it's parsing. If it were to provide io.Reader in the API, it would have to essentially do an io.ReadAll() before continuing almost guaranteeing extra work / memory utilization (origBytes->io.Reader->copyBytes->Parse rather than origBytes->Parse)</p></pre>thorhs: <pre><p>True, but what if you are reading from a network resource? Or a compressed file, or any number of other readers?</p>
<p>I can't believe the ParseFile does anything different than read from a reader internally, but I have not looked at the source though. </p></pre>kylewolfe: <pre><blockquote>
<p>I can't believe the ParseFile does anything different than read from a reader internally</p>
</blockquote>
<p>Don't be afraid to have a look. ParseFile is simply a wrapper, but in the end it still winds up here: <a href="https://github.com/golang/go/blob/master/src/text/template/parse/parse.go" rel="nofollow">https://github.com/golang/go/blob/master/src/text/template/parse/parse.go</a></p></pre>lstokeworth: <pre><p>I wonder why the argument to <a href="https://godoc.org/text/template#Template.Parse" rel="nofollow">Parse</a> is string and not []byte.</p></pre>4ad: <pre><p>Because this makes it really easy to write templates in your Go source code.</p></pre>dominikh: <pre><p>Because templates aren't data, they're text. It's really the same reason why you use a string in <code>fmt.Println("Hello, world")</code>.</p>
<p>Templates are usually hard-coded or generated from specific building blocks. They're not usually data that is read from some external source (with the exception of files; but you consider a Go source file text and not data, too. Same goes for templates.)</p></pre>zeroZshadow: <pre><p>I'm guessing because text could be in utf8, and be 2 bytes per character. Making it a string means that the parser does not have to deal with the conversion.</p></pre>lstokeworth: <pre><p>The parser assumes UTF-8 encoding for strings and I would assume that it would do the same for []byte.</p></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传