DEV Community

fy
fy

Posted on

golang, why doesn't string type inherit all the methods of strings package?

#go

I am too scared to write this question on stackOverflow because those guys will feed me to the wolves, something unique about golang community! they are a ruthless bunch on SO.

Getting back to the point, basically the question. i know you can do something like

type Str string

func (s Str) toByteArr() {
    fmt.Println([].byte(s))
}

func main()  {
    Str("Looking good today!").toByteArr()
}

But this kind of open gates for all kind of types floating around and i imagine could become harder to handle at some point.

I am just thinking wouldn't it be easy like any other language "string".method(); to have all those methods from strings package available to you, rather then you trying to find ways how to make this more easy to write strings.doSomething(myString).

If not, what is the reason?

Top comments (1)

Collapse
 
bykof profile image
Michael Bykovski

a byte slice and a string can be easily type casted:

s := "abc"
t := []byte(s)
u := string(t)