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
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.
To split any string only at the last occurrence, using strings.LastIndex
import (
"fmt"
"strings"
)
func main() {
x := "a_ab_daqe_sd_ew"
lastInd := strings.LastIndex(x, "_")
fmt.Println(x[:lastInd]) // o/p: a_ab_daqe_sd
fmt.Println(x[lastInd+1:]) // o/p: ew
}
Note, strings.LastIndex returns -1 if substring passed(in above example, "_") is not found
Since this is for path operations, and it looks like you don't want the trailing path separator, then path.Dir does what you're looking for:
fmt.Println(path.Dir("a/b/c/d/e"))
// a/b/c/d
If this is specifically for filesystem paths, you will want to use the filepath package instead, to properly handle multiple path separators.