MENU

Go 学习笔记:集合map与范围range

August 24, 2021 • Read: 267 • Golang

集合range

Go 语言同时支持了集合这种东西,它是一种无序的键值对的集合,可以通过key来快速检索数据,也可以像切片或者数组那样被迭代。不过集合是无序的,我们无法确定他的返回顺序,因为他是基于hash表实现的

/*
 * @Author: NorthCityChen
 * @LastEditTime: 2021-08-24 11:20:54
 * @Description:
 * @Website: https://grimoire.cn
 * Copyright (c) NorthCityChen All rights reserved.
 */
package main

import (
    "fmt"
)

func main() {
    trans := map[string]int{"one": 1, "two": 2, "three": 3}
    fmt.Println(trans["one"])
    fmt.Println(trans["two"])
    fmt.Println(trans["three"])

    trans["four"] = 4
    fmt.Println(trans["four"])

}

如果想要删除集合也是非常简单的,go提供了delete函数

/*
 * @Author: NorthCityChen
 * @LastEditTime: 2021-08-24 11:22:46
 * @Description:
 * @Website: https://grimoire.cn
 * Copyright (c) NorthCityChen All rights reserved.
 */
package main

import (
    "fmt"
)

func main() {
    trans := map[string]int{"one": 1, "two": 2, "three": 3}
    fmt.Println(trans["one"])
    fmt.Println(trans["two"])
    fmt.Println(trans["three"])

    trans["four"] = 4
    fmt.Println(trans["four"])

    delete(trans, "four")
    fmt.Println(trans["four"])
}

范围range

range关键字是用来在for循环中迭代数组、切片、通道或集合的元素的东西,在数组和切片中,它返回元素的索引和索引对应的值,在集合中返回key-value对

遍历切片

/*
 * @Author: NorthCityChen
 * @LastEditTime: 2021-08-24 11:10:14
 * @Description:
 * @Website: https://grimoire.cn
 * Copyright (c) NorthCityChen All rights reserved.
 */
package main

import (
    "fmt"
)

func main() {
    slice := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}
    var sum int = 0
    for idx, i := range slice {
        sum += i
        fmt.Println("idx:", idx)
    }
    fmt.Println(sum)
}

遍历数组

/*
 * @Author: NorthCityChen
 * @LastEditTime: 2021-08-24 11:10:14
 * @Description:
 * @Website: https://grimoire.cn
 * Copyright (c) NorthCityChen All rights reserved.
 */
package main

import (
    "fmt"
)

func main() {
    slice := [20]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}
    var sum int = 0
    for idx, i := range slice {
        sum += i
        fmt.Println("idx:", idx)
    }
    fmt.Println(sum)
}

遍历集合

/*
 * @Author: NorthCityChen
 * @LastEditTime: 2021-08-24 11:15:27
 * @Description:
 * @Website: https://grimoire.cn
 * Copyright (c) NorthCityChen All rights reserved.
 */
package main

import (
    "fmt"
)

func main() {
    trans := map[string]int{"one": 1, "two": 2, "three": 3}
    // fmt.Println(trans["one"])
    for key, value := range trans {
        fmt.Println(key, value)
    }
    trans["four"] = 4
    for key, value := range trans {
        fmt.Println(key, value)
    }
}
Archives Tip
QR Code for this page
Tipping QR Code