Learn Golang in Days - Day 11

栏目: Go · 发布时间: 7年前

Learn Golang in Days - Day 11

要点

  • Range
  • Go语言中range关键字用于for循环中迭代数组array,slice,channel or map 的元素。在数组和切片中它返回元素的索引和索引对应的值,在集合中返回key-value的key值。
  • range 可以遍历数组,切片
  • range 可以遍历字符串
  • range 可以遍历map

实例

package main

import "fmt"


func main() {
    // ---------------- 定义切片 ----------------
    //定义slice
    nums := []int {1,2,3}
    sum := 0

    for _,num := range nums {
        fmt.Printf("%d,", num)
        sum += num
    }

    fmt.Printf("\nsum= %d\n",sum)
    fmt.Println()

    for i,num := range nums {
        fmt.Printf("nums[%d]=%d\n",i, num)
        sum += num
    }


    // ------------------ Map -------------------
    kvs := map[string]string{"a":"apple","b":"banana"}
    for k,v := range kvs {
        fmt.Printf("%s -> %s\n", k,v)   
    }

    //----------------- String ------------------
    s := "This is a tiger"
    for i,c := range s {
        fmt.Printf("[%d]=%c\n",i,c) 
    }
}

以上所述就是小编给大家介绍的《Learn Golang in Days - Day 11》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。

Clean Architecture

Clean Architecture

Robert C. Martin / Prentice Hall / 2017-9-20 / USD 34.99

Practical Software Architecture Solutions from the Legendary Robert C. Martin (“Uncle Bob”) By applying universal rules of software architecture, you can dramatically improve developer producti......一起来看看 《Clean Architecture》 这本书的介绍吧!

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具

html转js在线工具
html转js在线工具

html转js在线工具