http://golang.org/doc/effective_go.html#initialization describes a way to attach methods to arbitrary object in the Go programming language. As an example, they site the string
method for a newly defined ByteSize
type:
type ByteSize float64
const (
_ = iota; // ignore first value by assigning to blank identifier
KB ByteSize = 1<<(10*iota);
MB;
GB;
TB;
PB;
YB;
)
The ability to attach a method such as String to a type makes it possible for such values to format themselves automatically for printing, even as part of a general type.
func (b ByteSize) String() string {
switch {
case b >= YB:
return fmt.Sprintf("%.2fYB", b/YB)
case b >= PB:
return fmt.Sprintf("%.2fPB", b/PB)
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("%.2fB", b)
}
What's not clear to me is the following: if ByteSize
and func (b ByteSize) String() string
are both defined in a package somewhere, I import that package but want to customize the display of ByteSize
by writing using my own string method, how does Go know whether to call my own string method or the previously defined string method? Is it even possible to redefine string?