• More types: structs, slices, and maps Part3


    1.Slices of slices

    Slices can contain any type, including other slices.

    1. package main
    2. import (
    3. "fmt"
    4. "strings"
    5. )
    6. func main() {
    7. // Create a tic-tac-toe board.
    8. board := [][]string{
    9. []string{"_", "_", "_"},
    10. []string{"_", "_", "_"},
    11. []string{"_", "_", "_"},
    12. }
    13. // The players take turns.
    14. board[0][0] = "X"
    15. board[2][2] = "0"
    16. board[1][2] = "X"
    17. board[1][0] = "0"
    18. board[0][2] = "X"
    19. for i := 0; i < len(board); i++ {
    20. fmt.Printf("%s\n", strings.Join(board[i], " "))
    21. }
    22. }

    2.Appending to a slice

    It is common to append new elements to a slice, and so Go provides a built-in append function. The documentation of the built-in package describes append.

    func append(s []T, vs ...T) []T

    The first parameter s of append is a slice of type T, and the rest are T values to append to the slice.

    The resulting value of append is a slice containing all the elements of the original slice plus the provided values.

    If the backing array of s is too small to fit all the given values a bigger array will be allocated. The returned slice will point to the newly allocated array.

    1. package main
    2. import "fmt"
    3. func main() {
    4. var s []int
    5. printSlice(s)
    6. // append works on nil slices.
    7. s = append(s, 0)
    8. printSlice(s)
    9. // The slice grow as needed.
    10. s = append(s, 1)
    11. printSlice(s)
    12. // we can add more than one element at a time
    13. s = append(s, 2, 3, 4)
    14. printSlice(s)
    15. }
    16. func printSlice(s []int) {
    17. fmt.Printf("len=%d cap=%d %v\n", len(s), cap(s), s)
    18. }

    3.Range

    The range form of the for loop iterates over a slice or map.

    When ranging over a slice, two values are returned for each iteration. The first is the index, and the second is a copy of the element at that index.

    1. package main
    2. import "fmt"
    3. var pow = []int{1, 2, 4, 8, 16, 32, 64, 128}
    4. func main() {
    5. for i, v := range pow {
    6. fmt.Printf("2**%d == %d\n", i, v)
    7. }
    8. }

    4.Range continued

    You can skip the index or value by assigning to _.

    for i, _ := range pow
    for _, value := range pow

    If you only want the index, you can omit the second variable.

    for i := range pow

    1. package main
    2. import "fmt"
    3. func main() {
    4. pow := make([]int, 10)
    5. for i := range pow {
    6. pow[i] = 1 << uint(i) // == 2**i
    7. }
    8. for _, value := range pow {
    9. fmt.Printf("%d\n", value)
    10. }
    11. }

    5.Maps

    A map maps keys to values.

    The zero value of a map is nil. A nil map has no keys, nor can keys be added.

    The make function returns a map of the given type, initialized and ready for use.

    1. package main
    2. import "fmt"
    3. type Vertex struct {
    4. Lat, Long float64
    5. }
    6. var m map[string]Vertex
    7. func main() {
    8. m = make(map[string]Vertex)
    9. m["Bell Labs"] = Vertex{
    10. 40.68433, -74.39967,
    11. }
    12. fmt.Println(m["Bell Labs"])
    13. }

    6.Map literals

    Map literals are like struct literals, but the keys are required.

    1. package main
    2. import "fmt"
    3. type Vertex struct {
    4. Lat, Long float64
    5. }
    6. var m = map[string]Vertex{
    7. "Bell Labs": Vertex{
    8. 40.68433, -74.39967,
    9. },
    10. "Google": Vertex{
    11. 37.42202, -122.08408,
    12. },
    13. }
    14. func main() {
    15. fmt.Println(m)
    16. }

    7.Map literals continued

    If the top-level type is just a type name, you can omit it from the elements of the literal.

    1. package main
    2. import "fmt"
    3. type Vertex struct {
    4. Lat, Long float64
    5. }
    6. var m = map[string]Vertex{
    7. "Bell Labs": {40.68433, -74.39967},
    8. "Google": {37.42202, -122.08408},
    9. }
    10. func main() {
    11. fmt.Println(m)
    12. }

    8.Mutating Maps

    Insert or update an element in map m:

    m[key] = elem

    Retrieve an element:

    elem = m[key]

    Delete an element:

    delete(m, key)

    Test that a key is present with a two-value assignment:

    elem, ok = m[key]

    If key is in m, ok is true. If not, ok is false.

    If key is not in the map, then elem is the zero value for the map's element type.

    Note: If elem or ok have not yet been declared you could use a short declaration form:

    elem, ok := m[key]

    1. package main
    2. import "fmt"
    3. func main() {
    4. m := make(map[string]int)
    5. m["Answer"] = 42
    6. fmt.Println("The value:", m["Answer"])
    7. m["Answer"] = 48
    8. fmt.Println("The value:", m["Answer"])
    9. delete(m, "Answer")
    10. fmt.Println("The value:", m["Answer"])
    11. v, ok := m["Answer"]
    12. fmt.Println("The value:", v, "Present?", ok)
    13. }

    9.Function values

    Functions are values too. They can be passed around just like other values.

    Function values may be used as function arguments and return values.

    1. package main
    2. import (
    3. "fmt"
    4. "math"
    5. )
    6. func compute(fn func(float64, float64) float64) float64 {
    7. return fn(3, 4)
    8. }
    9. func main() {
    10. hypot := func(x, y float64) float64 {
    11. return math.Sqrt(x*x + y*y)
    12. }
    13. fmt.Println(hypot(5, 12))
    14. fmt.Println(compute(hypot))
    15. fmt.Println(compute(math.Pow))
    16. }

    10.Function closures

    Go functions may be closures. A closure is a function value that references variables from outside its body. The function may access and assign to the referenced variables; in this sense the function is "bound" to the variables.

    For example, the adder function returns a closure. Each closure is bound to its own sum variable.

    1. package main
    2. import "fmt"
    3. func adder() func(int) int {
    4. sum := 0
    5. return func(x int) int {
    6. sum += x
    7. return sum
    8. }
    9. }
    10. func main() {
    11. pos, neg := adder(), adder()
    12. for i := 0; i < 10; i++ {
    13. fmt.Println(
    14. pos(i),
    15. neg(-2*i),
    16. )
    17. }
    18. }
  • 相关阅读:
    java项目进度跟踪管理系统
    【Linux】基本指令-入门级文件操作(二)
    【数据结构与算法】- 图(算法)
    分布式消息队列RocketMQ介绍
    elementui 表格自动滚动
    K-Means聚类算法---C++
    PyTorch学习笔记(一)
    “金九银十”必刷!薪资瓶颈突破,阿里推出的面试指南(全彩版)
    Docker基础学习
    通过Power Platform自定义D365 CE 业务需求 - 3. 使用Microsoft Power应用程序
  • 原文地址:https://blog.csdn.net/u011868279/article/details/133682004