Go中的函数冲突

huangapple go评论99阅读模式
英文:

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)
}

对我来说不清楚的是:如果 ByteSizefunc (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&lt;&lt;(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 &gt;= YB:
		return fmt.Sprintf(&quot;%.2fYB&quot;, b/YB)
	case b &gt;= PB:
		return fmt.Sprintf(&quot;%.2fPB&quot;, b/PB)
	case b &gt;= TB:
		return fmt.Sprintf(&quot;%.2fTB&quot;, b/TB)
	case b &gt;= GB:
		return fmt.Sprintf(&quot;%.2fGB&quot;, b/GB)
	case b &gt;= MB:
		return fmt.Sprintf(&quot;%.2fMB&quot;, b/MB)
	case b &gt;= KB:
		return fmt.Sprintf(&quot;%.2fKB&quot;, b/KB)
	}
	return fmt.Sprintf(&quot;%.2fB&quot;, 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.

huangapple
  • 本文由 发表于 2009年11月14日 05:02:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/1731905.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定