Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Go: partial string reference

Say I have a long string. I’d like to pass part of that string to another function for processing (read-only). The C way would be something like that

void dosomething(char *str, int start, int end) { /*...*/ }

Ofcourse I could do the same in go

func dosomething(str *string, int start, int end) { /*...*/ }

But with any other type than string I would just use a slice

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

func dosomething(str []byte) { /*...*/ }

which is way cleaner and much more compact. But slicing a string creates a new string instead of a slice reference.

Whats the intended way of passing partial string references? (I already have a string and I feel like casting it back to []byte is a waste of resources.)

Edit: It wont copy the string. The question just answered itself.

>Solution :

Slicing a string does not create a new underlying slice.

somestr[2:4] is effective and will not create a new slice. It will only create a new string header with a different start and end point of the same underlying byte slice.

The only exception is, when you don’t set a start or end point (somestr[:]), this will create a copy of the underlying byte slice.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading