How to get a substring from a string of runes in golang?

John picture John · Feb 25, 2015 · Viewed 8.2k times · Source

I found this, https://groups.google.com/forum/#!topic/golang-nuts/YyKlLwuWt3w but as far as I can tell, the solutions didn't work for me.

If you use the method of treating a string as a slice(str[:20]), it breaks off in the middle of characters and we get "ال�".

Edit: I believe I could write a function and do it as a multiple of 3's as runes are int32 (32bits/(8bits/byte)). I would first have to check if there are runes.

Answer

user1804599 picture user1804599 · Feb 25, 2015

Just convert it to a slice of runes first, slice, then convert the result back:

string([]rune(str)[:20])