unicodegorune

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


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.


Solution

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

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