开发者

Function collisions in 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 de开发者_开发知识库fined 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜