After strings.Split, get the last element?

2,069 views
Skip to first unread message

xobk...@gmail.com

unread,
Dec 4, 2013, 11:23:36 PM12/4/13
to golan...@googlegroups.com
In general, how can I get the last element of an array or a slice?

In particular, after split a string, how can I get the last element?

info := strings.Split("a=1,b=2,c=3,d=4", ",")
lastInfo := info[len(info)-1]
detail := strings.Split(lastInfo, "=")

seems a little awkward ...

Kevin Gillette

unread,
Dec 5, 2013, 12:07:54 AM12/5/13
to golan...@googlegroups.com, xobk...@gmail.com
`x[len(x)-1]` is the way to do so, and was chosen compared to x[-1] both for explicit clarity, and to avoid subtle bugs.

Kevin Gillette

unread,
Dec 5, 2013, 12:10:15 AM12/5/13
to golan...@googlegroups.com, xobk...@gmail.com
As a side note, len(x) is very cheap to evaluate at runtime, though negative indexing would have had to do that same computation anyway.
Reply all
Reply to author
Forward
0 new messages