我爱占星网 我爱占星网
首页
编程
java
php
前端
首页 编程 java php 前端

如何获得切片的最后一个元素?

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]

For removing it:

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

See this page about slice tricks

Bit less elegant but can also do:

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

近期文章

  • interface {}是什么意思?
  • Go如何更新第三方软件包?
  • 如何确定interface {}值的“真实”类型?
  • 有没有办法在Golang中迭代整数范围?
  • 如何使用Go有效地下载大文件?
  • 如何在http get请求中设置标题?
  • 与brew一起安装go,并运行getour
  • golang在另一个文件中声明的“未定义”功能?
  • Go中的fmt.Println()和println()有什么区别?
  • Go中的缩进:制表符还是空格?
  • 如何“测试”项目中的所有测试?
  • 在Go中提取子字符串
  • 声明切片还是制作切片?
  • Go / Golang将日志写入文件
  • 为什么不能用`copy()`复制切片?
  • go get中的“无法识别的导入路径”
  • 如何找出切片中的元素位置?
  • 如何使用go get安装软件包?
  • 如何使用yyyyMMddHHmmss格式格式化当前时间?
  • 为什么可以键入别名函数并在不进行强制转换的情况下使用它们?

Copyright ©2022 我爱占星 All Rights Reserved.

浙ICP备2022030071号-1

部分图文来自网络,如有侵犯您的版权,请告诉我们删除

友情链接:代码精华