Skip to content

How to Reverse a String in Golang

The challenge

Complete the solution so that it reverses the string passed into it.

'world' => 'dlrow' 'word' => 'drow'
Code language: PHP (php)

The solution in Golang

Option 1:

package solution func Solution(word string) (out string) { for _, v := range word { out = string(v) + out } return }
Code language: Go (go)

Option 2:

package solution import "strings" func Solution(word string) string { var b strings.Builder for i:=len(word)-1; i>-1; i-- { b.WriteByte(word[i]) } return b.String() }
Code language: Go (go)

Option 3:

package solution import "strings" func Solution(word string) string { var reversed []string for i := range(word) { reversed = append(reversed, string(word[len(word)-1-i])) } return strings.Join(reversed, "") }
Code language: Go (go)

Test cases to validate our solution

package solution_test import ( . "" . "" ) var _ = Describe("Test Example", func() { It("should test that the solution returns the correct value", func() { Expect(Solution("world")).To(Equal("dlrow")) Expect(Solution("hello")).To(Equal("olleh")) Expect(Solution("")).To(Equal("")) Expect(Solution("h")).To(Equal("h")) }) })
Code language: Go (go)

See also  Remove dotted outline around anchors
Notify of
Inline Feedbacks
View all comments
Would love your thoughts, please comment.x