How to reverse a string in Golang

In Golang (v1.62.2), there is no built-in method to reverse a string, so we will create our own function to serve this purpose.

Algorithm

Let’s go through the approach to solving this problem first.

  • Step 1: Define a function that accepts a string.
  • Step 2: Iterate over the input string and prepend the characters one by one to the resultant string.
  • Step 3: Return the resultant string.

Code

The code below demonstrates how to reverse a string.

package main
import "fmt"
// function to reverse string
func reverseString(str string) (result string) {
// iterate over str and prepend to result
for _ , v := range str {
result = string(v) + result
}
return
}
func main() {
str := "Educative-Edpresso"
fmt.Println(str)
// invoke reverseString
fmt.Println(reverseString(str))
}

Explanation

  • Line 5: We create the reverseString() function.

  • Line 6: The function accepts a string, iterates over it, and prepends each character to result. At the end of the function, it returns result.

  • Line 15: We declare a string str inside the main() function.

  • Line 17: We output str on the console.

  • Line 19: We invoke the reverseString function, pass str as an argument, and output the result on the console.

New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources