Golang的for循环中使用两个变量的等价写法是什么?

huangapple go评论73阅读模式
英文:

Golang for loop with 2 variables equivalent?

问题

我正在尝试理解Go语言的语法,但有些东西即使他们解释了也很难理解。

例如:

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

我将其翻译为以下代码:

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

我的问题是,在第一个代码中,for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1,j似乎没有条件,所以在我的代码中,我不知道如何解决它。

英文:

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 &lt; 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 &lt; 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 &lt; 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.

答案1

得分: 1

这是另一种更易读且产生相同结果的方法。
唯一的区别是变量j的作用域发生了改变。

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)
}
英文:

This is another way 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 &lt; len(r)/2; i++ {
          r[i], r[j] = r[j], r[i]
          j--
      }
      return string(r)
}

huangapple
  • 本文由 发表于 2021年12月27日 08:29:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/70490764.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定