Reverse an array in golang, not inplace.

PHOTO EMBED

Wed Oct 30 2024 03:49:20 GMT+0000 (Coordinated Universal Time)

Saved by @manasm11 #go #golang

// Reverse returns a new slice with the elements of the input slice in reverse order.
func Reverse[T any](arr []T) []T {
	n := len(arr)
	reversed := make([]T, n) // Create a new slice of the same length

	for i := 0; i < n; i++ {
		reversed[i] = arr[n-1-i] // Copy elements from end to start
	}

	return reversed
}
content_copyCOPY