find the last element in an array in go

To find the last element in an array in Go, you can use the index of the last element, which is the length of the array minus one. You can then access the last element using that index.

Here is an example:

main.go
arr := [4]int{1, 2, 3, 4}
last := arr[len(arr)-1]
fmt.Println(last) // Output: 4
81 chars
4 lines

In this example, we have an array arr with four integers. We calculate the index of the last element using len(arr)-1, which is 3. We then use this index to access the last element of the array, which is 4. The output of this program is 4.

related categories

gistlibby LogSnag