Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are string functions not defined on the string type?

Tags:

string

go

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.

like image 838
rpkamp Avatar asked Jan 19 '15 11:01

rpkamp


2 Answers

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

like image 139
nussjustin Avatar answered Oct 13 '22 11:10

nussjustin


string is one of the predeclared type in the builtin package.

Those functions in strings couldn't have been defined as method using a predeclared type as a receiver: that would have required to define a type alias (to the underlying type string, in order to attach methods to it).

A method declaration uses a receiver which has a Type, which in turn does not include any of the predeclared types (bool byte complex64 complex128 error float32 float64 int int8 int16 int32 int64 rune string uint uint8 uint16 uint32 uint64 uintptr).

Or (which is done here), one uses functions in a dedicated package 'strings'.
That seems coherent with the fact that the type string itself has no fields: its content doesn't have to "receive" the method, it can simply be used by a function.

like image 44
VonC Avatar answered Oct 13 '22 12:10

VonC