Created
March 21, 2022 09:50
-
-
Save hyle/14b1e95a86f55fab17dbe7ac7104f643 to your computer and use it in GitHub Desktop.
reverses a slice in place
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import "fmt" | |
func reverse[T any](s []T) { | |
for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 { | |
s[i], s[j] = s[j], s[i] | |
} | |
} | |
func main() { | |
a := [...]int{0, 1, 2, 3, 4, 5} | |
reverse(a[:]) | |
fmt.Println(a) // "[5 4 3 2 1 0]" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment