dor65412 2015-01-19 11:26
浏览 100
已采纳

为什么在字符串类型上未定义字符串函数?

I was just wondering why the string functions in Google Go are defined in a strings package as opposed to on the string data type itself. They could have easily done

func (s string) ToUpper() string {
}

instead of the current

func ToUpper(s string) string {
}

in the strings package.

My guess is that if you want to implement a custom version of ToUpper on a custom type that extends string (i.e., type MyString string), you have no way to access the builtin ToUpper anymore on that type, but I can't find any support on this.

  • 写回答

2条回答 默认 最新

  • douzun4443 2015-01-19 11:42
    关注

    The short answer is: "To keep the language simple."

    Go as a language only allows methods to be defined on types that are in the same package, but because string (like other builtin types) is implemented in the language itself, there is no way to add methods to it, without complicating the language / compiler.

    It's also partly, because of how Go was designed.

    See this mail from Rob Pike (one of the creators of Go) for more information:

    Go does not have methods on basic types because the designers of the language did not want methods defined for basic types, in part because of the knock-on effect they might have on interfaces. I believe we are all still comfortable with that decision. Others may feel differently.

    -rob

    And this one too:

    We simply didn't understand what the implications would be; there's nothing to explain. Go was designed with caution.

    In that vein, look at the size of the strings library. Making all that functionality methods on the basic type would, as Andrew said, complicate the language. Why complicate the language with such trivial things when it can be achieved by a library, which is more maintainable, easier to extend, and more flexible? The language is much simpler the way things are.

    -rob

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器