Return last item of strings.Split() slice in Golang

You should assign the results of the split to a variable, instead of calling it twice.

ss := strings.Split(msg, ".")
s := ss[len(ss)-1]

(Notice that this allows (or maybe forces) you to deal with the case where ss is empty or something else unexpected explicitly, before indexing it.)

If you're doing this over and over again, and it offends you having to use two lines (or two lines plus error handling) instead of one, you can abstract it into a function easily:

func lastString(ss []string) string {
    return ss[len(ss)-1]
}

s1 := lastString(strings.Split("example.txt", "."))
s2 := lastString(strings.Split("example.jpg", "."))

After all, passing the result of a function as an argument has essentially the same effect as binding it to a variable.


strings.LastIndex makes this quite neat:

s := "Hello,Stack,Overflow"
last := s[strings.LastIndex(s, ",")+1:]
fmt.Println(last)

returns "Overflow". If the search string isn't found it returns the whole string, which is logical.

Playground here