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.
Let’s go through the approach to solving this problem first.
The code below demonstrates how to reverse a string.
package mainimport "fmt"// function to reverse stringfunc reverseString(str string) (result string) {// iterate over str and prepend to resultfor _ , v := range str {result = string(v) + result}return}func main() {str := "Educative-Edpresso"fmt.Println(str)// invoke reverseStringfmt.Println(reverseString(str))}
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.