A brief summary of the Arrays Slices Maps Range operations in the Go language tutorial

  • 2020-05-09 18:44:29
  • OfStack

An array of Arrays:

In the go language the array array is an ordered set of elements of a particular length.


package main import "fmt" func main() {     // So here we create 1 A length of 5 An array of . this 1 The initial value of the array of groups is zero-valued . The integer is 0
    var a [5]int
    fmt.Println("emp:", a)     // Can be achieved by array[index] = value Grammar assignment
    a[4] = 100
    fmt.Println("set:", a)
    fmt.Println("get:", a[4])     // The built-in len The function returns the length of the array
    fmt.Println("len:", len(a))     // Declare the default initial value of the array through this syntax
    b := [5]int{1, 2, 3, 4, 5}
    fmt.Println("dcl:", b)     // The array type is 1 Dimensional, but you can create multidimensional array structures by combining them
    var twoD [2][3]int
    for i := 0; i < 2; i++ {
        for j := 0; j < 3; j++ {
            twoD[i][j] = i + j
        }
    }
    fmt.Println("2d: ", twoD)
}
$ go run arrays.go
emp: [0 0 0 0 0]
set: [0 0 0 0 100]
get: 100
len: 5
dcl: [1 2 3 4 5]
2d:  [[0 1 2] [1 2 3]]

Sliced Slices:

Slices is the key data type in the Go language, which has a stronger access interface than an array (arrays).


package main import "fmt" func main() {     // With an array of ( arrays ), slices And the type of the element it contains 1 To (not the number of elements). Use built-in make Command, build 1 A nonzero length void slice Object. So here we create 1 A contains 3 A string of characters . ( Initialize to zero zero-valued)
    s := make([]string, 3)
    fmt.Println("emp:", s)     // We can do things like arrays 1 The sample is set up and read.
    s[0] = "a"
    s[1] = "b"
    s[2] = "c"
    fmt.Println("set:", s)
    fmt.Println("get:", s[2])     // The length you get is the length you set.
    fmt.Println("len:", len(s))     // In contrast to these basic operations, slices support 1 More sophisticated features. There are 1 One is built in append Can be in the existing slice Add on object 1 Two or more values. Be careful about what you return append Object to get the latest addition of the element slice Object.
    s = append(s, "d")
    s = append(s, "e", "f")
    fmt.Println("apd:", s)     //Slices It can also be copied. Here we are going to s Copy to the c Length, 1 Cause.
    c := make([]string, len(s))
    copy(c, s)
    fmt.Println("cpy:", c)     //Slices support "slice" Operation, the syntax is slice[low:high] (that is, the interception slice ). The following code retrieves these characters: s[2], s[3], and s[4] .
    l := s[2:5]
    fmt.Println("sl1:", l)     // Intercept from the beginning to each 5 Characters (except values)
    l = s[:5]
    fmt.Println("sl2:", l)     // From the first 2 The characters (including) start to intercept to the end 1 a
    l = s[2:]
    fmt.Println("sl3:", l)     // We can put declarations and assignments in 1 Line.
    t := []string{"g", "h", "i"}
    fmt.Println("dcl:", t)     //Slices Can be combined into multidimensional arrays. inside 1 d slices Objects can vary in length 1 Dot is not the same as multidimensional array 1 The sample.
    twoD := make([][]int, 3)
    for i := 0; i < 3; i++ {
        innerLen := i + 1
        twoD[i] = make([]int, innerLen)
        for j := 0; j < innerLen; j++ {
            twoD[i][j] = i + j
        }
    }
    fmt.Println("2d: ", twoD)
}

Note that slices and arrays are two different data types, but their fmt.Println printing methods are similar.


$ go run slices.go
emp: [  ]
set: [a b c]
get: c
len: 3
apd: [a b c d e f]
cpy: [a b c d e f]
sl1: [c d e]
sl2: [a b c d e]
sl3: [c d e f]
dcl: [g h i]
2d:  [[0] [1 2] [2 3 4]]

Check out this article to see how the Go team designed and implemented slices in go.

Maps: key value pairs

Maps is the associated data type in the Go language (sometimes referred to in other languages as a hash table [hashes] or dictionary [dicts])


package main import "fmt" func main() {     // Use built-in make Come & 1 empty map . make(map[ Key type ] Value types )
    m := make(map[string]int)     // Set the key / Value pairs are used classically name[key] = val Syntax.
    m["k1"] = 7
    m["k2"] = 13     // print map It's going to output all the key-value pairs inside
    fmt.Println("map:", m)     // Gets the value of a key
    v1 := m["k1"]
    fmt.Println("v1: ", v1)     //len The function will get map In the key / Number of value pairs
    fmt.Println("len:", len(m))     // Use built-in delete Function from map Remove the key / The value of
    delete(m, "k2")
    fmt.Println("map:", m)     // Optional first 2 The return value can be indicated map Contains the value of this key. Avoid empty value 0 or "" Ambiguity.
    _, prs := m["k2"]
    fmt.Println("prs:", prs)     // You can do it too 1 The line completes the declaration and assignment
    n := map[string]int{"foo": 1, "bar": 2}
    fmt.Println("map:", n)
}

Note that map output format is map when printed using fmt.Println [k:v k:v].


$ go run maps.go
map: map[k1:7 k2:13]
v1:  7
len: 2
map: map[k1:7]
prs: false
map: map[foo:1 bar:2]

Scope of Range:

range can be enumerated over a variety of data structures. Let's look at how to use it on the previous data structure.


package main import "fmt" func main() {     // This is what we use range Go to ask 1 a slice And. Using arrays is very similar to this
    nums := []int{2, 3, 4}
    sum := 0
    for _, num := range nums {
        sum += num
    }
    fmt.Println("sum:", sum)     // Use it on an array range Will be introduced to index And the value. In the above example we do not need to use the ordinal number of the element, so we use a blank character "_" Omitted. Sometimes we really need to know its index.
    for i, num := range nums {
        if num == 3 {
            fmt.Println("index:", i)
        }
    }     //range It can also be used in map The key value of.
    kvs := map[string]string{"a": "apple", "b": "banana"}
    for k, v := range kvs {
        fmt.Printf("%s -> %s\n", k, v)
    }     //range It can also be used for enumeration Unicode A string. The first 1 Is the index of the character 2 Is the character ( Unicode Is the value of) itself.
    for i, c := range "go" {
        fmt.Println(i, c)
    }
}
$ go run range.go
sum: 9
index: 1
a -> apple
b -> banana
0 103
1 111


Related articles: