How to get first and last element of slice in Golang?
In this example, you will learn to get first and last element of Slice and remove last element from Slice.
The composite data type
Slice
is commonly used as the colloquial construct for indexed data in Go.The type
[]intSlice
is a Slice with elements of type integer.len
function is used to fetch last element of Slice and remove last element from Slice.
Example
package main
import "fmt"
func main() {
intSlice := []int{1, 2, 3, 4, 5}
fmt.Printf("Slice: %v\n", intSlice)
last := intSlice[len(intSlice)-1]
fmt.Printf("Last element: %v\n", last)
first := intSlice[:0]
fmt.Printf("First element: %d\n", first)
remove := intSlice[:len(intSlice)-1]
fmt.Printf("Remove Last: %v\n", remove)
}
Output
Slice: [1 2 3 4 5]
Last element: 5
First element: [1]
Remove Last: [1 2 3 4]
Most Helpful This Week
How to remove all line breaks from a string in Golang?
GO Program to take user input and addition of two strings
How do you handle HTTP server health checks in Go?
How to read current directory using Readdir?
How to check if an item exists in Slice in Golang?
Golang program for implementation of Interpolation Search
Make Your Retirement Luxurious with These 5 Game-Changing Altcoins
What is JSX?
Type assertion in Go Programming Language
5 Must-Know Blockchain Trends for 2024 and Beyond