Come ottenere l'ultimo elemento di una fetta?


167

Qual è il modo Go per estrarre l'ultimo elemento di una sezione?

var slice []int

slice = append(slice, 2)
slice = append(slice, 7)

slice[len(slice)-1:][0] // Retrieves the last element

La soluzione sopra funziona, ma sembra imbarazzante.

Risposte:


297

For just reading the last element of a slice:

sl[len(sl)-1]

For removing it:

sl = sl[:len(sl)-1]

See this page about slice tricks


34
Thanks a bunch! Even though it does seem silly they didn't add the -1 index Python has...
Morgan Wilde

3
I do like the -1 from Python, although it often lead to hard-to-debug errors.
weberc2

11
They left it outside consciously. It was non-obvious and prone to errors. Go overall is circumspect about 'too much meaning'; it also doesn't feature method/operator overloading, default values for function params, etc. which IMHO goes in a similar philosophical vein. See this discussion and others: groups.google.com/forum/#!topic/golang-nuts/yn9Q6HhgWi0
Toni Cárdenas

2
I am not sure but I got panic: runtime error: index out of range for profiles[len(profiles)-1].UserId, I guess the length of the slice is 0 so it panics?
tom10271

@tom10271 Yes, you can't get the last element of a slice if there's no such element, ie. if there are no elements at all.
Toni Cárdenas

-10

Bit less elegant but can also do:

sl[len(sl)-1: len(sl)]

3
That's the same as sl[len(sl)-1:], but that returns a slice containing the last element, rather than just the last element. play.golang.org/p/kcThrqa-64c
Victor
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.