Why would you want to use Printf over Print or Println?

agolangf · · 443 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p><em>EDIT</em> I had no idea what a formatted string was until some people answered this..I know, I&#39;m a complete newb. Thanks everybody, this was real helpful.</p> <p>After running some throwaway programs, here&#39;s what I&#39;ve gathered about <code>Print</code>, <code>Printf</code>, and <code>Println</code>:</p> <ul> <li><code>Print</code> will print number variables, and will not include a line break at the end.</li> <li><code>Printf</code> will not print number variables, and will not include a line break at the end.</li> <li><code>Println</code> will print number variables, and will include a line break at the end.</li> </ul> <p>It seems to me the clear loser here is <code>Printf</code>, since it&#39;s the only one of the three that cannot print number variables.</p> <p>So, my questions is: why would you use <code>Printf</code>? Does it save memory or something?</p> <hr/>**评论:**<br/><br/>bbatha: <pre><p><code>Printf</code> is for printing <code>f</code>formatted strings. Such as <code>fmt.Printf(&#34;%X&#34;, 0xFF)</code> with print a number in hex. And it can lead to more readable printing <code>fmt.Printf(&#34;(%d/%d) operations on %s succeeded&#34;, successes, failures, ops)</code>.</p> <p>I fully listing of formatters is available in the <a href="https://golang.org/pkg/fmt/#hdr-Printing" rel="nofollow"><code>fmt</code> godoc.</a> There are related functions for printing to strings and files in general.</p></pre>stoned_phillips: <pre><p>Interesting. I didn&#39;t think I was getting the whole picture in my definitions. That helps a lot. Thanks.</p></pre>chmikes: <pre><p>There is another difference between Print and Println. Println will add a space between printed values and Print won&#39;t.</p> <p>Println(&#34;a&#34;,&#34;b&#34;,&#34;c&#34;) -&gt; &#34;a b c\n&#34; Print(&#34;a&#34;,&#34;b&#34;,&#34;c&#34;) -&gt; &#34;abc&#34;</p></pre>shovelpost: <pre><p>Or you can use <code>println</code> that doesn&#39;t even need an import. :D</p> <p>But seriously, <code>Printf</code> is about formatting. Check the different ways you can print structs.</p> <pre><code>foo := struct{ name string }{&#34;foo&#34;} fmt.Printf(&#34;%v\n&#34;, foo) fmt.Printf(&#34;%+v\n&#34;, foo) fmt.Printf(&#34;%#v\n&#34;, foo) fmt.Printf(&#34;foo is of type %T\n&#34;, foo) </code></pre> <p><a href="https://play.golang.org/p/sxT3ab1aEU" rel="nofollow">Playground link</a></p></pre>ruertar: <pre><p>I always use <code>Printf()</code> because it is faster/more efficient in the most common case where you just want to print a string.</p> <p>This is because the first argument is a <code>string</code> instead of an <code>interface{}</code> so the fast path doesn&#39;t require a <code>reflect.TypeOf()</code> etc. to print. It just prints the string.</p></pre>robpike: <pre><p>False efficiency and potentially a bug. If you have <code> var s string = f() fmt.Printf(s) </code> or even just <code> fmt.Printf(f()) </code> the result will be incorrect and ugly if the string contains an unexpected percent sign. Use <code> fmt.Printf(&#34;%s&#34;, s) </code> or <code> fmt.Print(s) </code> because that&#39;s what it&#39;s for. By the way, the fast path for that doesn&#39;t use reflection either. You&#39;re doing premature optimization, the root of all bad /r/ posts.</p></pre>Fwippy: <pre><p>Oh, there are many many more reasons for bad posts than that.</p></pre>9gPgEpW82IUTRbCzC5qr: <pre><p>printf seems like a sane default considering one often comes back to expand print statements with state</p></pre>ruertar: <pre><p>Ouch! This really smarts. First: Of course you&#39;re right, that was a bad post.</p> <p>So, I <em>completely</em> agree that this is premature optimization and I actually complain about this sort of thing. I saw an opportunity to talk about how <code>Printf()</code> with one argument doesn&#39;t use reflection but frankly the few ns of speedup is <em>not</em> why I do this. I think I replied with this mainly as a way to signal, &#34;hey -- I know this thing...&#34;</p> <p>I do tend to use <code>Printf()</code> but mainly because I come from C and it is almost a habit. Though I never use <code>Printf()</code> without a format string -- I&#39;m aware of the pitfalls of that.</p> <p>I&#39;m sorry for the crappy post and point taken! I&#39;ll try to be more thoughtful in the future.</p></pre>TheHusky11: <pre><p>Umm what? </p> <pre><code>package main import ( &#34;fmt&#34; ) func main() { num := 3 fmt.Printf(&#34;I have %d apples\n&#34;, num) } </code></pre> <p><a href="https://play.golang.org/p/Hi6rXaNGZI" rel="nofollow">https://play.golang.org/p/Hi6rXaNGZI</a></p> <p>The f in printf stands for formatted. It can print any variable type.</p></pre>rmasci: <pre><p>When I have a complex string I want to print out it&#39;s just easier using fmt.Printf. Example:</p> <pre><code>// println fmt.Println(&#34;Last Name: &#34;+lastName+&#34;, First Name: &#34; + firstName + &#34;, Age: &#34;+age+&#34;, Service: &#34;+service+&#34;, Rank: &#34;+rank+&#34;, Unit: &#34;+unit+&#34;.&#34;) // printf fmt.Printf(&#34;Last Name: %s, First Name: %s, Age: %s, Service: %s, Rank: %s, Unit: %s.\n&#34;,lastName,firstName,age,service,rank,unit) </code></pre> <p><a href="https://play.golang.org/p/lyV5CN9bhS" rel="nofollow">https://play.golang.org/p/lyV5CN9bhS</a></p> <p>To me its a lot easier to write that line using fmt.Printf over fmt.Println. In generating the example I had a much harder time with the println than I did with the printf. Another example would be if you only want to print out 2 decimals from a float:</p> <pre><code>a:=100.0/3.0 fmt.Println(&#34;A=&#34;,a) fmt.Printf(&#34;A= %.2f\n&#34;,a) </code></pre> <p>It&#39;s a lot easier (for me at least) to just stick the raw number in to Printf and let it do the work and format it with 2 decimals. My advice is to read the manual. Printf is MUCH more powerful than Println, and nearly every time I use println most of the time before the program is done I&#39;ve changed it to Printf because it just can&#39;t do what I want it to do. </p></pre>dchapes: <pre><blockquote> <p>here&#39;s what I&#39;ve gathered about</p> </blockquote> <p>That&#39;s your problem. Don&#39;t &#34;gather&#34;, don&#39;t guess, <a href="https://golang.org/pkg/fmt#Printf" rel="nofollow">just RTFM</a> and it should be completely clear and obvious.</p></pre>

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

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