To find the smallest element in an array in Go, you can iterate over the entire array and keep track of the smallest element seen so far. This can be achieved by initializing the smallest element variable with the first element of the array and updating it whenever a smaller element is encountered.
Here's an implementation of this approach:
main.go244 chars15 lines
This function takes an integer array arr
as input and returns the smallest element in the array. If the array is empty, it returns -1 to indicate an error.
We initialize min
to be the first element of the array arr
. Then, we iterate over each element of the array and update min
if a smaller element is encountered.
You can call this function like this:
main.go110 chars4 lines
Output:
main.go22 chars2 lines
gistlibby LogSnag