为什么在字符串类型上未定义字符串函数? [英] Why are string functions not defined on the string type?

查看:98
本文介绍了为什么在字符串类型上未定义字符串函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想知道为什么Google Go中的字符串函数是在strings包中定义的,而不是在string数据类型本身上定义的.他们本可以轻松完成

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

代替当前

func ToUpper(s string) string {
}

包中的

.

in the strings package.

我的猜测是,如果您想在扩展string(即type MyString string)的自定义类型上实现ToUpper的自定义版本,则您将无法再访问内置的ToUpper类型,但是对此我找不到任何支持.

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.

推荐答案

简短的答案是:保持语言简单."

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

作为一种语言,仅允许在同一包中的类型上定义方法,但是由于string(与其他内置类型一样)是在语言本身中实现的,因此无法向其中添加方法,而不会使语言/编译器复杂化.

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.

部分原因是因为Go的设计方式.

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

请参阅Rob派克(Go的创建者之一)的这封邮件更多信息:

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

Go没有基本类型的方法,因为 语言不希望为基本类型定义方法,部分原因是 对接口可能产生的连锁影响.我相信我们 所有人仍然对此决定感到满意.其他人可能会有不同的感觉.

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

还有这一个:

我们根本不理解其中的含义;有 没什么可解释的. Go的设计非常谨慎.

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

这篇关于为什么在字符串类型上未定义字符串函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆