Open In App

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.

Examples:

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

Example 1:




// Golang program to access the first
// and last element of the slice
  
package main
  
import "fmt"
  
func main() {
  
    // Declaring & Defining
    // the Slice
    sliceOfInt := []int{2, 3, 4, 5, 6}
  
    // Printing the Slice
    fmt.Printf("Slice: %v\n", sliceOfInt)
  
    // Accessing zeroth index
    // i.e. first element
    first := sliceOfInt[0]
  
    // Printing first element
    fmt.Printf("First element: %d\n", first)
  
    // Accessing length(slice)-1
    // index i.e. last
    // element
    last := sliceOfInt[len(sliceOfInt)-1]
  
    // Printing last element
    fmt.Printf("Last element: %v\n", last)
  
}

Output:

Slice: [2 3 4 5 6]
First element: 2
Last element: 6

Example 2:




// Golang program to access the first
// and last element of the slice
package main
  
import "fmt"
  
func main() {
  
    sliceOfFloat := []float32{2.5, 3.2, 4.1, 5.7, 6.9}
    fmt.Printf("Slice: %v\n", sliceOfFloat)
  
    first := sliceOfFloat[0]
    fmt.Printf("First element: %v\n", first)
  
    last := sliceOfFloat[len(sliceOfFloat)-1]
    fmt.Printf("Last element: %v\n", last)
  
}

Output:

Slice: [2.5 3.2 4.1 5.7 6.9]
First element: 2.5
Last element: 6.9

Article Tags :