Golang Initialization描述了一种将方法附加到Go编程语言中的任意对象的方法.作为示例,它们显示String了新定义ByteSize类型的方法:
type ByteSize float64
const (
_ = iota; // ignore first value by assigning to blank identifier
KB ByteSize = 1<<(10*iota);
MB;
GB;
TB;
PB;
YB;
)
Run Code Online (Sandbox Code Playgroud)
将诸如String之类的方法附加到类型的功能使得这些值可以自动格式化以进行打印,即使是作为常规类型的一部分.
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)
}
Run Code Online (Sandbox Code Playgroud)
我不清楚的是:如果ByteSize和func (b ByteSize) String() string都在一个包中定义,我导入该包但是想ByteSize通过使用我自己的字符串方法自定义显示,Go如何知道是否调用我自己的字符串方法或先前定义的字符串方法?是否有可能重新定义字符串?
Sco*_*les 10
如果你想要新的方法,你打算包装一个类型,所以你要定义
type MyByteSize ByteSize
func (b MyByteSize) String() string{
}
Run Code Online (Sandbox Code Playgroud)
您不能在我认为定义的模块之外的类型上定义方法.