Composite data of Go learning notes

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

Composite data that is understood by the individual is compounded by other data formats.

1. Array

The type format of an array is a single data cell type + length composition, such as [2]int, where [2] represents the length of the array, and int represents each cell as an integer.

The element operation of an array is also done by manipulating the subscript, i.e., arr[1], to remove the 2nd element of the array arr, and the array subscript starts at 0.

The length of the array can be obtained by Len (arr) for the length of the array arr.

1-1 Declaration and initialization

Array declaration format is var array name [array length] element type

For example:

var arr [2]intarr[0] = 1//After declaration, you can use index to assign values


After the array is declared, the initial value of each data cell is the default for the cell data type, for example, int is 0, string is empty ""

The declaration can also be initialized at the same time

var arr [2]int = [2]int{1, 2}

The format of the initialization data is: Array type + curly brace + Array data

You can also use: = to abbreviate

Arr: = [2]int{1, 2}

Use: = can omit array length and use [...] to get go to automatically calculate the length of the array

Arr: = [...] Int{1, 2}

Ps:go in the ... There are a lot of other places, which usually means the number is determined at compile time or runtime.

1-2 Nesting of arrays

An array can also be an element of another array, thus forming a multidimensional array (nested arrays)

Arr: = [2][2]int{[2]int{1, 2}, [2]int{3, 4}}

can be shortened to

Arr: = [2][2]int{{1, 2}, {3, 4}}

The same element types must be identical in the same latitude as the nested arrays, for example

var arr [2][2]int
Arr0: = [2]int{1, 2}
Arr[0] = Arr0

ARR1: = [1]int{1}
ARR[1] = arr1//Compile Error: Cannot use ARR1 (Type [1]int) as type [2]int in Assignment

1-3 length of the array

The length of the array must be declared when it is given, and it cannot be changed after giving it, and the Len function can be used to get the length of the array.

1-4 out of bounds for arrays

If the subscript is less than 0 or greater than or equal to the length of the array

A, subscript is a numeric constant, the compilation error: Index out of bounds

B, subscript is a dynamic variable, then the execution of the time detection, error message is runtime Error:index out of range

1-5 Assigning values to arrays

Array assignment is different from string, because string cannot be changed, so only the address of the string is passed, and array because can change, so to copy the entire content, in memory there will be 2 copies of data exist

ARR1: = [2]int{1, 2}
var arr2 [2]int

ARR2 = arr1
ARR2[1] = 3
Fmt. Print (arr1[1])//Output 2

Because array assignments require space, most often use slice to reduce memory consumption by passing the address of an array in slices.

2, Slice

Slice can be thought of as a special class array structure, which points to an array type of data, using the same array, out-of-bounds report the same as an array of errors

2-1 Slice's statement

var s []int//differs from array, length is unspecified, if indicated is an array

After Slice is declared, the value of slice is nil, can be initialized by default by make, or it can be initialized with a specific value.

The default value is initialized (the following initialization uses a short format: =)

S: = make ([]int, 4, 4)///The first 4 is the length of the slice, the second is the capacity of the slice, explained below

Equivalent to S: = []int{0, 0, 0, 0}

3 scenarios where the specific value is initialized

A, point to an already existing array

Arr: = [4]int{1, 2, 3, 4}

S: = Arr[1:3]

b, create an (anonymous) array and point to the array

s: = []int{1, 2, 3, 4}

C, based on another slice

S1: = []int{1, 2, 3, 4}

S2: = S1[2:4]

Structure of the 2-2 slice

The structure of the slice consists of 3 parts: pointers, lengths, and capacities that point to the underlying data (starting subscript).

The length is the same as an array, with the Len function, and the capacity with the CAP function

Array_a: = [10]byte{' A ', ' B ', ' C ', ' d ', ' e ', ' f ', ' g ', ' h ', ' I ', ' J '}
Slice_a: = Array_a[2:5]

The structure of the example is as shown (image from Https://github.com/astaxie/build-web-application-with-golang)


According to the mathematical interval definition, the interval of array[i:j] should be [i,j], that is, the index of the element contained is I <= index < J

The Array_a[2:5] In the example above contains the following elements: Array_a[2],array_a[3], array_a[4]

Slice_a len () equals J-i.

Slice_a cap () equals Len (array_a)-I

If I is 0,j as the length of the array, you can ignore the

Slice_a: = array_a[:]//contains all elements of the array

Some operation functions of 2-3 Slice

In addition to the make, Len, and CAP functions already mentioned above, Slice also supports append, copy operation functions

Copy (DST, SRC) copies elements from the source SRC to the target DST, and returns the number of copied elements, in the go language, almost all in the order that the target parameter is before the source parameter

Copy supports copying string types to byte slices, except that they must be of the same type

var byte_slice = make ([]byte, 2)

Copy (Byte_slice, "HI")

Append (DST, SRC) appends the source SRC to the target DST, where the source src can be one or more single-type values

Int_slice: = []int{1}

Int_slice = Append (Int_slice, 2, 3)//[1, 2, 3]

You can also make another slice, but you need to specify it after the slice ... Special markings

Int_slice: = []int{1}

Int_slice2: = []int{2, 3}
Int_slice = Append (Int_slice, int_slice2 ...)//[1, 2, 3]

The pass-through append also supports copying string types to byte slices, which need to be specified later ... Special markings

var byte_slice = []byte ("Hello")
Byte_slice = Append (Byte_slice, "World" ...)

Some quick actions for 2-4 slice

Insert element x after position I

Slice = append (Slice[:i], append ([]t{x}, Slice[i:] ...) ...) T means that a data type is represented

Insert a slice after position I

Slice1 = Append (Slice[:i], append (Slice2, slice[i:] ...) ...)

Insert J empty element after position I

Slice = append (Slice[:i], append (Make ([]t, J), Lice[i:] ...) ...)

To append a single element to a slice

Slice = Append (slice, x)

Slice Append slice Content

Slice1 = Append (Slice1, Slice2 ...)

Adding J empty elements to a slice

Slice = append (slice, make ([]t, J) ...)

Copy slices

Slice2 = Make ([]t, Len (Slice1))

Copy (Slice2, Slice1)

Delete the I element in a slice

Slice = append (Slice[:i], slice[i+1:] ...)

Delete a specified set of elements in a slice [i:j]

Slice = append (Slice[:i], slice[j:] ...)

Popup first element

X, slice = slice[0], slice[1:]

Popup last Element

X, slice = Slice[len (slice)-1], Slice[:len (Slice)-1]

3. Map

A map is called a dictionary (Dictionary) in some languages, or a hash table, which refers to the correspondence of some type of value to another type of value.

3-1 Declaration and initialization

Map declaration format is var map name map[index Type] element type

For example:

var map1 map[int]string

When the map is declared, it is not initialized, and the value of map is nil and cannot be assigned, and it needs to be initialized with make

Map1 = Make (map[int]string)

The declaration can also be initialized at the same time

var map1 map[int]string = Make (map[int]string)

You can also use: = to abbreviate

MAP1: = Make (map[int]string)

You can also initialize the value directly without make.

MAP1: = map[int]string{}

When initialized with the specified value, the Key:value format is required

MAP1: = map[int]string{1: "1", 2: "2"}

3-2 Map operation

Built-in function len generic can be used on a map to return how many elements are in the current map

Map because there is no memory limit, can be easily added, can also be very convenient to delete, delete need to use Delete, for example, delete map1 key 1 element is

Delete (MAP1, 1)

Gets the value of the key in the map

V: = Map[key]

Determine if a key exists

V, OK: = Map[key]

Key exists in map, V = Value,ok = true of key

Key does not exist in map, V = T (default), OK = False

Add or change value

Map[key] = value

Note that map does not guarantee the order of Key-value storage

Key must be a type that supports the comparison operator (= = \! =), such as number, string, pointer, array, struct, interface (the interface implementation type must support the comparison operator), not function, map, slice

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.