Golang Initialization describes how to bind methods to an arbitrary object in the Go programming language. As an example, they show a method Stringfor a new type ByteSize:
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 bind a method such as String to a type allows these forms to automatically format them for printing, even as part of a generic 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)
}
It is not clear that if ByteSizeand func (b ByteSize) String() stringare both defined in the package somewhere, I import this package, but I want to customize the display ByteSizeby writing with his own method of string, like Go know whether to recall its own method of string or before a specific method of string? Is it possible to override a string?
emmby