Home > Software engineering >  Golang for loop with 2 variables equivalent?
Golang for loop with 2 variables equivalent?

Time:12-27

I am trying to understand golang's syntax in doc but some things are hard to understand even they explain it.

For example:

func Reverse(s string) string {
   r := []rune(s)
   for i, j := 0, len(r)-1; i < len(r)/2; i, j = i 1, j-1 {
    r[i], r[j] = r[j], r[i]
   }
   return string(r)
}

I translated it to raw code:

func reverseString2(str string) string {
    var array = []rune(str)
    for i := 0; i < len(str)/2; i   {
        for j := len(str) - 1; ???? ; j-- {
          // ---
        }
    }
    return string(array)
}

my problem is that in the first one for i, j := 0, len(r)-1; i < len(r)/2; i, j = i 1, j-1, j does not seems to have a condition so in my code I dont know how to solve it.

CodePudding user response:

This is another method that is easier to read and leads to the same result. The only difference is that the scope of variable j has become different.

func Reverse(s string) string {
      r := []rune(s)
      j := len(r) - 1
      for i := 0; i < len(r)/2; i   {
          r[i], r[j] = r[j], r[i]
          j--
      }
      return string(r)
}
  •  Tags:  
  • go
  • Related