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.
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:
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
-1 from Python, although it often lead to hard-to-debug errors.
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?
Bit less elegant but can also do:
sl[len(sl)-1: len(sl)]
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
-1index Python has...