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'

The solution in Golang

Option 1:

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

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()
}

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, "")
}

Test cases to validate our solution

package solution_test
import (
  . "github.com/onsi/ginkgo"
  . "github.com/onsi/gomega"
)
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"))
  })
})