切片的最后一个元素

切片的最后一个元素

问题描述:

什么是 Go $ c>方法用于提取切片的最后一个元素

var slice []int

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

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

上面的解决方案工作,但看起来很尴尬。

The solution above works, but seems awkward.

sl[len(sl)-1]

删除它:

For removing it:

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

请参阅关于切片技巧的页面