]> Cypherpunks repositories - gostls13.git/commitdiff
Documentation: Fix a bug in the example in Constants subsection
authorJames Fysh <james.fysh@gmail.com>
Fri, 27 Aug 2010 21:54:16 +0000 (07:54 +1000)
committerRob Pike <r@golang.org>
Fri, 27 Aug 2010 21:54:16 +0000 (07:54 +1000)
Not a bug per-se, the issue is that the fmt.Sprintf method inside the
ByteSize.String() method ends up calling itself to generate the String
representation of the ByteSize value.  Infinite loops are bad.

    Updated as per review comments

R=r
CC=golang-dev
https://golang.org/cl/1974046

doc/effective_go.html

index 8083e9fbc9484d7ebe46e802796f6f5a2da7a949..a04152e49c875cdd6dd1a6f48ab6017e8d2dfa35 100644 (file)
@@ -1539,26 +1539,29 @@ automatically for printing, even as part of a general type.
 func (b ByteSize) String() string {
     switch {
     case b &gt;= YB:
-        return fmt.Sprintf("%.2fYB", b/YB)
+        return fmt.Sprintf("%.2fYB", float64(b/YB))
     case b &gt;= ZB:
-        return fmt.Sprintf("%.2fZB", b/ZB)
+        return fmt.Sprintf("%.2fZB", float64(b/ZB))
     case b &gt;= EB:
-        return fmt.Sprintf("%.2fEB", b/EB)
+        return fmt.Sprintf("%.2fEB", float64(b/EB))
     case b &gt;= PB:
-        return fmt.Sprintf("%.2fPB", b/PB)
+        return fmt.Sprintf("%.2fPB", float64(b/PB))
     case b &gt;= TB:
-        return fmt.Sprintf("%.2fTB", b/TB)
+        return fmt.Sprintf("%.2fTB", float64(b/TB))
     case b &gt;= GB:
-        return fmt.Sprintf("%.2fGB", b/GB)
+        return fmt.Sprintf("%.2fGB", float64(b/GB))
     case b &gt;= MB:
-        return fmt.Sprintf("%.2fMB", b/MB)
+        return fmt.Sprintf("%.2fMB", float64(b/MB))
     case b &gt;= KB:
-        return fmt.Sprintf("%.2fKB", b/KB)
+        return fmt.Sprintf("%.2fKB", float64(b/KB))
     }
-    return fmt.Sprintf("%.2fB", b)
+    return fmt.Sprintf("%.2fB", float64(b))
 }
 </pre>
 <p>
+(The <code>float64</code> conversions prevent <code>Sprintf</code> 
+from recurring back through the <code>String</code> method for 
+<code>ByteSize</code>.)
 The expression <code>YB</code> prints as <code>1.00YB</code>,
 while <code>ByteSize(1e13)</code> prints as <code>9.09TB</code>.
 </p>