dou4381 2009-11-13 21:02
浏览 39
已采纳

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条回答 默认 最新

  • dongyou4411 2009-11-13 21:13
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试
  • ¥20 问题请教!vue项目关于Nginx配置nonce安全策略的问题
  • ¥15 教务系统账号被盗号如何追溯设备
  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效
  • ¥15 再不同版本的系统上,TCP传输速度不一致
  • ¥15 高德地图2.0 版本点聚合中Marker的位置无法实时更新,如何解决呢?
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题