英文:
Function collisions in Go
问题
Golang 初始化 描述了一种在 Go 编程语言中将方法附加到任意对象的方式。例如,他们展示了一个新定义的 ByteSize
类型的 String
方法:
type ByteSize float64
const (
_ = iota; // 通过赋值给空白标识符忽略第一个值
KB ByteSize = 1<<(10*iota);
MB;
GB;
TB;
PB;
YB;
)
能够附加像 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)
}
对我来说不清楚的是:如果 ByteSize
和 func (b ByteSize) String() string
都在某个包中定义,我导入该包但想通过编写自己的字符串方法来自定义 ByteSize
的显示,Go 如何知道是调用我的字符串方法还是之前定义的字符串方法?重新定义字符串是可能的吗?
英文:
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?
答案1
得分: 10
意图是让您在需要为类型添加新方法时进行封装,因此您可以定义:
type MyByteSize ByteSize
func (b MyByteSize) String() 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论