How to Get First and Last Element of Slice in Golang?
Go language slice is more powerful, flexible, convenient than an array, and is a lightweight data structure. Slice is a variable-length sequence which stores elements of a similar type, you are not allowed to store different type of elements in the same slice. It is just like an array having an index value and length, but the size of the slice is resized they are not in fixed-size just like an array. Internally, slice and an array are connected with each other, a slice is a reference to an underlying array. It is allowed to store duplicate elements in the slice. The first index position in a slice is always 0 and the last one will be (length of slice – 1).
Accessing First Element: It’s easy to access the first element with the zeroth index of Slice.
Accessing Last Element: The Last element is the element at the index position that is the length of the Slice minus 1.
Input : sliceOfInt=[2, 3, 4, 5, 6] Output : First element : 2 Last element : 6 Input : sliceOfFloat=[4.5, 3.4, 6.6, 5.2, 2.1] Output : First element : 4.5 Last element : 2.1
Slice: [2 3 4 5 6] First element: 2 Last element: 6
Slice: [2.5 3.2 4.1 5.7 6.9] First element: 2.5 Last element: 6.9