Skip to content

Instantly share code, notes, and snippets.

@developer1622
Created July 24, 2021 10:40
Show Gist options
  • Save developer1622/caaa8d384dd7362dc83bfe2a937d43f7 to your computer and use it in GitHub Desktop.
Save developer1622/caaa8d384dd7362dc83bfe2a937d43f7 to your computer and use it in GitHub Desktop.
Reverse string in Golang
// reverse takes string 's' and reverses it and returns it.
// reverse does not create new string.
func reverse(s string) string {
// as strings are immutable in Golang, we have to convert
// to rune slice, which can be modified
// FYI: https://zetcode.com/golang/rune/
rStr := []rune(s)
for i, j := 0, len(rStr)-1; i < j; i, j = i+1, j-1 {
// swap the letters of the string,
// like first with last and so on.
rStr[i], rStr[j] = rStr[j], rStr[i]
}
// convert the rune to string and return.
return string(rStr)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment