DEV Community

fy
fy

Posted on

2 1

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?

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

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)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more