回答

收藏

Go中有foreach循环吗?

技术问答 技术问答 355 人阅读 | 0 人回复 | 2023-09-12

foreachGo语言中有结构吗?我可以用 a 迭代切片或数组for吗?
8 q- |# `" [9 N$ F' S                                                               
$ e" v& r2 K* E4 U+ t7 C  i7 o    解决方案:                                                                , u& d5 i8 ]& o% [6 X" t$ d
                                                                带有“range”子句的“for句子遍历了数组、切片、字符串或映射的所有项目,或通道上接收到的值。对于每个项目,它将迭代值分配给相应的迭代变量,然后执行该块。+ A4 C5 K3 u4 c! @
举个例子:
5 N1 G- U8 U. T# k5 ^/ B/ [
    for index,element := range someSlice      / index is the index where we are    // element is the element from someSlice for where we are}
    & o* L, c% S4 U" s, p1 a% [- @' ]
如果不关心索引,可以用_:
& Z5 B& V3 ~% K3 L4 d
    for _,element := range someSlice      / element is the element from someSlice for where we are}
    . a& R4 N  c( R8 y! ?. K6 ~7 Q. a
下划线_是空白标识符,匿名占位符。
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则