Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating over go string and making string from chars in go

Tags:

string

go

I started learning go and I want to implement some algorithm. I can iterate over strings and then get chars, but these chars are Unicode numbers.

How to concatenate chars into strings in go? Do you have some reference? I was unable to find anything about primitives in official page.

like image 826
Sławosz Avatar asked Dec 08 '22 14:12

Sławosz


1 Answers

Iterating over strings using range gives you Unicode characters while iterating over a string using an index gives you bytes. See the spec for runes and strings as well as their conversions.

As The New Idiot mentioned, strings can be concatenated using the + operator.

The conversion from character to string is two-fold. You can convert a byte (or byte sequence) to a string:

string(byte('A'))

or you can convert a rune (or rune sequence) to a string:

string(rune('µ'))

The difference is that runes represent Unicode characters while bytes represent 8 bit values.

But all of this is mentioned in the respective sections of the spec I linked above. It's quite easy to understand, you should definitely read it.

like image 71
nemo Avatar answered Dec 11 '22 09:12

nemo