How to get the last element of a slice in Golang

How to get the last element of a slice in Golang

In this post we will give you information about How to get the last element of a slice in Golang. Hear we will give you detail about How to get the last element of a slice in GolangAnd how to use it also give you demo for it if it is necessary.

we will learn how to get the last element of a slice in Golang.

In Go, the elements in the silce can be accessed by using its index number, where the first element index is [0], the second element index is [2], etc.

Getting the last element

To access the last element of a slice, we can use the slice expression [] by passing len(slice)-1 in Go.

Here is an example, that gets the last element 45 from the prices slice:

prices := []int{15,25,35,45}lastElement := prices[len(prices)-1]fmt.Println(lastElement)

Output:

45

Hope this code and post will helped you for implement How to get the last element of a slice in Golang. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs

For More Info See :: laravel And github

We're accepting well-written guest posts and this is a great opportunity to collaborate : Contact US