tags:

views:

118

answers:

1

http://golang.org/doc/effective_go.html#initialization describes a way to attach methods to arbitrary object in the Go programming language. As an example, they site the 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?

+3  A: 

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.

Scott Wales
Right. Other languages solve this same problem by overriding a method on a subclass. But in Go, you have the advantage that the object itself doesn't have to be of the new type. You can get a ByteSize from anywhere, save it into a MyByteSize-typed variable, and use your own method instead.
Kevin Conner