go语言基础之for循环和range的使用

在go语言中,for循环和php的for循环类似,用分号分为三段,初始值;条件,迭代值。

range是一个关键词,获取一个可迭代变量的key和walue

以下是学习代码

package main

import "fmt"

func main() {
	fmt.Println("以下为for循环的使用")
	var str string = "hello golang 我来了"

	for key := 0; key < len(str); key++ {
		fmt.Printf("str 下标为 %d 的值为 %c \n ", key, str[key])
	}

	fmt.Println("以下为range的使用说明")
	for key, value := range str {
		fmt.Printf("str 下标为%d 的值为 %c \n", key, value)
	}
}

运行代码结果如下:

以下为for循环的使用
str 下标为 0 的值为 h
 str 下标为 1 的值为 e
 str 下标为 2 的值为 l
 str 下标为 3 的值为 l
 str 下标为 4 的值为 o
 str 下标为 5 的值为
 str 下标为 6 的值为 g
 str 下标为 7 的值为 o
 str 下标为 8 的值为 l
 str 下标为 9 的值为 a
 str 下标为 10 的值为 n
 str 下标为 11 的值为 g
 str 下标为 12 的值为
 str 下标为 13 的值为 æ
 str 下标为 14 的值为
 str 下标为 15 的值为
 str 下标为 16 的值为 æ
 str 下标为 17 的值为
 str 下标为 18 的值为 ¥
 str 下标为 19 的值为 ä
 str 下标为 20 的值为 º
 str 下标为 21 的值为
 以下为range的使用说明
str 下标为0 的值为 h
str 下标为1 的值为 e
str 下标为2 的值为 l
str 下标为3 的值为 l
str 下标为4 的值为 o
str 下标为5 的值为
str 下标为6 的值为 g
str 下标为7 的值为 o
str 下标为8 的值为 l
str 下标为9 的值为 a
str 下标为10 的值为 n
str 下标为11 的值为 g
str 下标为12 的值为
str 下标为13 的值为 我
str 下标为16 的值为 来
str 下标为19 的值为 了
  • 6
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

数据馅

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值