How to slice a rune in Go

16 March 2015   0 comments   Go

Mind That Age!

This blog post is 4 years old! Most likely, its content is outdated. Especially if it's technical.

Strangely this was hard. The solution looks easy but it took me a lot of time to get this right.

What I want to do is split a string up into a slice of parts. For example:

word := "peter"
for i := 1; i <= len(word); i++ {
    fmt.Println(word[0:i])
}

The output is:

p
pe
pet
pete
peter

Play here.

Now, what if the word you want to split contains non-ascii characters? As a string "é" is two characters internally. So you can't split them up. See this play and press "Run".

So, the solution is to iterate over the string and Go will give you an index of each unicode character. But you'll want to skip the first one.

word := "péter"
for i, _ := range word {
    if i > 0 {
        fmt.Println(word[0:i])
    }
}
fmt.Println(word)

You can play with it here in this play.

Now the output is the same as what we got in the first example but with unicode characters in it.

p
pé
pét
péte
péter

I bet this is obvious to the gurus who've properly read the documentation but it certainly took me some time to figure it out and so I thought I'd share it.

Comments

Your email will never ever be published

Related posts

Previous:
Air Mozilla on Roku 05 March 2015
Next:
Bye bye httpretty. Welcome back good old mock! 19 March 2015
Related by Keyword:
Fastest Python function to slugify a string 12 September 2019
Rust > Go > Python ...to parse millions of dates in CSV files 15 May 2018
Unzip benchmark on AWS EC2 c3.large vs c4.large 29 November 2017
Autocompeter is Dead. Long live Autocompeter! 09 January 2017
Go vs. Python 24 October 2014