如何获得切片的最后一个元素? [英] How to get the last element of a slice?
本文介绍了如何获得切片的最后一个元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
提取切片的最后一个元素的Go方法是什么?
What is the Go way for extracting the last element of a slice?
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.
推荐答案
仅读取切片的最后一个元素:
For just reading the last element of a slice:
sl[len(sl)-1]
要删除它:
sl = sl[:len(sl)-1]
请参见有关切片技巧的页面
这篇关于如何获得切片的最后一个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文