Golang Initialization describes a way to attach methods to arbitrary object in the Go programming language. As an example, they show a 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?
The intention is for you to wrap a type if you want new methods on it, so you would define
type MyByteSize ByteSize
func (b MyByteSize) String() string{
}
You can't define methods on a type outside of the module it was defined I believe.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With