5. Arrays, slices and dictionaries

1. Array:

Defined by:

Fixed length:

var x [ 5 ] int

Initially it is null.

This defines a fixed length.

Then 

x[0] = 1

 x[1] = 2

 x[2] = 3

 x[3] = 4

 x[4] = 5

 assign one by one

 

Unlimited length:

var x = [...] int {

1, 2, 3}

 

This case must have initial data

// Two traversal methods

package main

import (
    "fmt"
)

func main() {
    var a = [...] int { 1 , 2 , 3 }

    fmt.Println (only)

    // Traversal method one 
    for _, i := range(a) {
        fmt.Println(i)
    }

    // Traversal method two 
    for i := 0 ; i < len(a); i ++ {
        fmt.Println(a[i])
    }
}

 

2. Slicing

As the name implies, it is a piece cut from the array, and the subscript also starts from 0 , similar to the container in C++ , and the length is not fixed.

There are two properties:

capacity and length _ _ _ _

Two definitions:

First declare, then use make to initialize

// The first way to define
 // make(element type, len, capacity 
var x = make([] int , 5 , 10 )
 for i := 0 ; i < len(x); i++ {
    x[i] = i
}
fmt.Println(cap(x))
fmt.Println(len(x))
fmt.Println(x)
// Cut a piece directly from the array

 

// Second definition method

// Intercept format y[low_index : high_index] Intercept interval [low_index, high_index]

var y = [ 5 ] int { 1 , 2 , 3 , 4 , 5 }

var s1 = y [ 1 : 2 ]

var s2 = y[: 2 ]

var s3 = y [ 1 :]

var s4 = y[:]

fmt.Println(s1)

fmt.Println(s2)

fmt.Println (s3)

fmt.Println (s4)

The append function adds elements to the slice:

E.g:

var s1 = append( [] int {1, 2, 3}, 4, 5, 6}

s1  is  now [1, 2, 3, 4, 5, 6]

The change of memory is similar to the vector in C++ : because the slice needs random access, it needs a continuous space. If the number of elements exceeds the capacity , a new space will be opened up and the elements will be copied .

3. Dictionary

Similar to the map in the C++ standard library , there is a pair of key-value pairs  {key, value}key  which is equivalent to an index .

Two definitions:

Initialization data:

//It 's actually initializing the data

var x = map[string]string{

    "A": "Apple",

    "B": "Banane",

    "O": "Orange",

    "P": "Pear",

}

Initialized by the make function:

var y map[string]string

y = make(map[string]string)

y["A"] = "Apple"

y["B"] = "Banana"

y["O"] = "Orange"

y["P"] = "Pear"

Traverse:

for key, val := range x {

    fmt.Println("Key:", key, "Value:", val)

}

If you are not interested in the return value of key or value  , you can use _ instead

for _, val := range x {

    fmt.Println("Value:", val)

}

In addition , map supports random access , such as fmt.Println(x["A"])  , if the key has no corresponding value , the value is empty.

delete:

delete(x, “A”)

Delete the key - value pair with key "A"

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326369224&siteId=291194637