Golang for循环使用多个变量

由于Go没有逗号表达式,而++和–是语句而不是表达式,如果想在for中执行多个变量,需要使用平行赋值

for i, j := 1, 10; i < j; i,j=i+1,j+1 {  //死循环
    fmt.Println(i)
}

而不能写成

for i, j := 1, 10; i < j; i++,j++ {
    fmt.Println(i)
}

for的condition在每执行一次循环体时便会执行一次,因此在实际开发过程中需要注意不要让condition中计算简单而不是复杂。

for i,j :=0,len(str); i<j ; i++ {
    fmt.Println(str[i])
}

而不要写成

for i=0; i< len(str); i++ {
    fmt.Println(str[i])
}

另外for是遍历string,array,slice,map,chanel的方式,而使用保留字rang则能灵活的处理。rang是迭代器,能根据不同的内容,返回不同的东西。

for index,char := range string {}
for index,value := range array {}
for index,value := range slice {}
for key,value := range map {}

需要注意的是for range遍历string时得到的是字节索引位置和UTF-8格式rune类型数据(int32)。

for pos, value := range "Go在中国" {
    fmt.Printf("character '%c' type is %T value is %v, and start at byte position %d \n", value,value,value, pos)
    str :=string(value)  //convert rune to string
    fmt.Printf("string(%v)=>%s \n",value,str)
}

---------OutPut------------ 一个汉字占三个字节
character 'G' type is int32 value is 71, and start at byte position 0 
string(71)=>G 
character 'o' type is int32 value is 111, and start at byte position 1 
string(111)=>o 
character '在' type is int32 value is 22312, and start at byte position 2 
string(22312)=>在 
character '中' type is int32 value is 20013, and start at byte position 5 
string(20013)=>中 
character '国' type is int32 value is 22269, and start at byte position 8 
string(22269)=>

原文链接:https://www.cnblogs.com/junneyang/p/6072680.html

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值