Arrays and slices of go basics

array

Definition of an array:

An array is a fixed-length sequence of zero or more elements of the same data type

How to define an array:
var variable name[len] type

Example:
var a[5] int //array of 3 integers
var a[5]string //array of 3 strings

Like the above definition method, we specify the length of the array, but there are also the following definition methods:
var a=[...]int{1,2,3}
If the length of the array is replaced by..., then The length of the array is determined by the number of elements in the initialized array

Each element in the array is accessed by index, and the index starts from 0.
For example, the first element of the array var a[5]int is a[0], and
the length of the array is obtained by len(a)

Need to know here: the length of the array is also part of the array type, so know that [3]int and [4]int are different array types

By default, the initial value of the elements in a new array is the zero value of the element type.
For example, an array of certificate type, the default value is 0.

Initialize the array:

There are several ways:
var a = [5] int{1,2,3,4,5}
var a = [5] int{1,2,3}
var a = [...]int{1, 2,3,4}
var a = [5]string{1:"go",3:"python"}

Types of Arrays:
Value Types

traversing the array

Array traversal method:
var a = [3]int{1, 2, 3}
for i, v := range a {
fmt.Printf("%d %d\n", i, v)
}
Of ​​course if you don't need it Indexing works too:
var a = [3]int{1, 2, 3}
for _, v := range a {
fmt.Printf("%d\n", v)
}

Two-dimensional array

var a[3][2]

In fact, a two-dimensional array can be understood through an excel sheet, which is a matter of several rows and several columns. For example, the above example is a two-dimensional array with 3 rows and 2 columns.
Regarding the traversal of the two-dimensional array, create a two-dimensional array and loop the assignment, and then print the content
var c [3][2]int
for i := 0; i < 3; i++ {
for j := 0; j < 2 ; j++ {
c[i][j] = rand.Intn(10)
}
}
for i := 0; i < 3; i++ {
for j := 0; j < 2; j++ {
fmt.Printf("%d ", c[i][j])
}
fmt.Println()
}

Comparing arrays

If the element types of two arrays are the same, they can be compared with each other. For example, array a:= [2]int{1,2} and array b:=[2]int{3,4}
are both of int type, so You can use == to compare two arrays to see if the elements on both sides are exactly the same, use != to compare to see if the elements on both sides are different

The following example demonstrates more clearly

a := [2]int{1, 2}
b := [...]int{1, 2}
c := [2]int{3, 2}
d := [3]int{1, 2}
fmt.Println(a == b, a == c, b == c)
fmt.Println(a == d)

 In the above example, the result of the first print is true, false, false, and when the second print is added, it cannot be compiled because the two cannot be compared

slice slice

definition

slice represents a variable-length sequence of elements of the same type

Defining a slice is actually very similar to defining an array
var variable name []type
var b = []int

Compared with the array, slice seems to be an array with no length

 

Initialization of slice
var a[5] int //This is to define an array
var b[]int = a[0,2]
var b[]int = a[0:5]
var b[]int = a[:]
var b[]int = a[:3]

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

Also traversing slices and arrays is exactly the same

By comparing arrays and slices, we can actually find that the two are actually very similar, and of course the two do have a close relationship.

The underlying implementation of slice is an array, usually we call it the underlying array of slice.
Slice has three properties: pointer, length and capacity, as shown below

The pointer points to the first element of the array that can be accessed from the slice. This element is not necessarily the first element of the array. The
length refers to the number of elements in the slice, which cannot exceed the capacity of the slice.
The size of the capacity is from the beginning of the slice The number of elements to the last element of the underlying array
can be used to obtain the length and capacity of the slice through len and cap

Understand through the following example:
var s = [5]int{1, 2, 3, 4, 5}
var b = s[2:3]
var c = s[0:4]
Now ask the length and capacity of b, c Compared with the above definition, the length and capacity
are actually very easy to understand.
s is like the underlying array
of slice. For the slice of b, he starts slicing from the third element of the array. When slicing, the principle of left closing and right opening is used.

so the length of b is 1
for the capacity of b by definition we know from the third element of the array to the end of the array
so the capacity of b is 3

In this way, we can also easily obtain that the length of c is 3 and the capacity is 5

slice creation

The built-in function make can create a slice with the specified element type, length and capacity, where the capacity parameter can be omitted, so that the length and capacity of the default slice are equal

make([]type,len,cap)
make([]type,len)

Now talk about:
make([]type,len)
make([]type,len,cap)

Actually make creates an unnamed array and returns a slice of it; this array can only be accessed through slices.
The first: the slice returned by make([]type,len) refers to the entire array.
The second: make([]type,len,cap)slice only references the first len ​​elements of the array, but its capacity is the length of the array

Understand the creation process of slices through the following diagram:

 

About copy

This function is mainly a copy of the slice, and does not support arrays
to copy the elements in the second slice to the first slice. If the two added array slices are not the same size, they will be copied according to the number of elements in the smaller array slice.

s1 := []int{1, 2, 3, 7, 8}
s2 := []int{4, 5, 6}
copy(s2, s1)
fmt.Printf("%#v\n", s2)

 The result of printing s2 in this way is: []int{1, 2, 3}
Change the code to:

s1 := []int{1, 2, 3, 7, 8}
s2 := []int{4, 5, 6}
copy(s1, s2)
fmt.Printf("%#v\n", s1)

 The result of printing s1 in this way is: []int{4, 5, 6, 7, 8}
This copy is to copy the first three elements in s2 to the first three elements in s1, and perform the first three elements in s1. covered

About append

The built-in function append appends elements to the end of a slice

Understand through the following example, add each character of "hello go" to a slice cyclically

var runnes []rune
for _, v := range "hello,go" {
    runnes = append(runnes, v)
}
fmt.Printf("%q\n", runnes)

Example 2 Append directly to a slice that already has elements

s1 := []int{1, 2, 3}
s1 = append(s1, 4, 5)
fmt.Printf("%#v\n", s1)

If you want to append another slice directly to the current slice:

s1 := []int{1, 2, 3}
s2 := []int{4, 5}
s1 = append(s1, s2...)
fmt.Printf("%#v\n", s1)

 Here it is passed after s2... In fact, it is to expand the elements in s2 and then append into s1

In fact, the append function is very important to understand the working principle of slice. The following is a method defined for []int array slice:

func appendInt (x [] int, y int) [] int {
    var z [] int
    zlen := len(x) + 1
    if zlen <= cap(x) {
        //slice still has room for growth to expand the slice content
        z = x [: zlen]
    } else {
        //slice has no space, allocate a new underlying array for him
        //Of course, the strategy of the actual go bottom expansion may be much more complicated. Here is an example of doubling the expansion.
        zcap := zlen
        if zcap < 2*len(x) {
            zcap = 2 * len(x)
        }
        z = make([]int, zlen, zcap)
        copy(z, x)
    }
    z [len (x)] = y
    return z

 It can be seen from the above method:
every time appendInt will check whether the slice has enough capacity to store new elements in the array, if the slice capacity is enough, then he will define a new slice, note that the original is still referenced here The underlying array, then copy the new element y to the new position, and return a new slice, so that the parameter slice x we ​​pass in and the function return value slice z actually use the same underlying array.
If the capacity of the slice is not large enough to accommodate the growing element, the appendInt function must create a new underlying array of sufficient capacity to store the new element, then copy the element from the slice x to this array, and append the new element y to the end of the array. In this way, the returned slice z will refer to a different underlying array from the passed parameter slice z.

Comparing slices

Unlike arrays, slices cannot be compared, so you cannot use == to compare whether two slices have the same elements. The
only comparison operation allowed by slice is to compare with nill. The zero value of slice is nill
. Here are the things to note: The length and capacity of a slice with a value of nill are both zero, but this is not deterministic, because there are non-nill slices with a length and capacity of zero, so want to check whether a slice is or not use len(s) == 0 and not s == nill

Below is an example of collated practice slice usage

How to modify a string?

package main

import (
    "fmt"
)

func changeString(str1 string) {
    var runnes = [] rune (str1)
    runnes [0] = 'h'
    res := string(runnes)
    fmt.Println(res)
}

func main() {
    changeString("Hello,Go")
}

 

Here is to replace the initial uppercase h with lowercase

Look at another example:
implementing the inversion of a string

func reverseStr(str1 string) {
    var runes = [] rune (str1)
    var res string
    for i := len(runes) - 1; i >= 0; i-- {
        res += string(runes[i])
    }
    fmt.Println(res)
}

 The above method can realize the inversion of the string, of course, there is more than one method, and the following is also a method

func reverseStr2(str1 string) {
    var runes = []rune(str1)
    for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
        runes[i], runes[j] = runes[j], runes[i]
    }
    res := string(runes)
    fmt.Println(res)
}

I have been using rune in the above method, what is this thing? see next

The bottom layer of character-to-string in Go is stored in a byte array, and it is immutable.
When we loop a string through for key, value := range str, in fact, each value type returned is rune
And we know that what is enclosed in double quotes in go is the string string. There are two ways to represent the string in go:
one is byte, which represents the value of a single byte of utf-8 string; the other is rune, Represents a single unicode string
about an explanation on rune's official website:

rune is an alias for int32 and is equivalent to int32 in all ways. It is
used, by convention, to distinguish character values from integer values.

var a = "I love you go"
fmt.Println(len(a))

As mentioned above, the bottom layer of the string is a byte array, so when we use len to calculate the length, we actually get the length of the array, and a Chinese character occupies 3 bytes, so the above result is 11

At first glance, many people, especially beginners, may think that the length should be 5. In fact, if you want to convert to 4, you only need to go through the shrimp and rice method:

 var a = "I love you go"
fmt.Println(len([]rune(a)))

time and date type

Current time: now:= time.Now()

time.Now().Day()

time.Now().Minute()

time.Now().Month()

time.Now().Year()

time.Duration is used to represent nanoseconds

Some commonly used time constants

const (
Nanosecond Duration = 1
Microsecond =1000 * Nanosecond
Millisecond =1000 * Microsecond
Second =1000 * Millisecond
Minute =60 * Second
Hour =60 * Minute
)

 Note: If you want to format the time, you must pay special attention, you can only format it in the following ways:

fmt.Println(time.Now().Format("2006-01-02 15:04:05"))
The time in Format is fixed, because it is the birth time of the first program of go, and I don't know about go What do the developers think? I guess they want all those who learn go to remember this great moment.

Slice Processing Supplement

About slice deletion

package main

import "fmt"

func main() {
    index := 2
    var s = [] int {10,15,8,20}
    s = append(s[:index],s[index+1:]...)
    fmt.Println(s)
}

 

Guess you like

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