Why does the following Go program need the function's name to be String() and not anything else? -
i'm following book shows following example.
package main import ( "fmt" ) const ( kb = 1024 mb = 1048576 //kb * 1024 gb = 1073741824 //mb * 1024 tb = 1099511627776 //gb * 1024 pb = 1125899906842624 //tb * 1024 ) type bytesize float64 func (b bytesize) string() string { switch { case b >= pb: return "very big" case b >= tb: return fmt.sprintf("%.2ftb", b/tb) case b >= gb: return fmt.sprintf("%.2fgb", b/gb) case b >= mb: return fmt.sprintf("%.2fmb", b/mb) case b >= kb: return fmt.sprintf("%.2fkb", b/kb) } return fmt.sprintf("%db", b) } func main() { fmt.println(bytesize(2048)) fmt.println(bytesize(3292528.64)) }
when run program gives me following output (in human readable data size units).
2.00kb 3.14mb
but when change name of function called string() else, or if lower-case s in string, gives me following output.
2048 3.29252864e+06
what reason behind that? there string() function attached interface , our bytesize type satisfies interface? mean hell?
when define method named string
no parameters returning string, implement stringer
interface, documented here: https://golang.org/pkg/fmt/#stringer.
Comments
Post a Comment