英文:
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 < 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.
答案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 < len(r)/2; i++ {
r[i], r[j] = r[j], r[i]
j--
}
return string(r)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论