Golang Learning Notes (iv): Array, slice, Map_golang

Source: Internet
Author: User
Tags array length arrays data structures in python

One. Array

In the go language, an array is a value type (value)

All value type variables will produce a copy action when they are assigned and passed as parameters

If you are the parameter type of a function, the parameter occurs when the function is called, and the contents of the incoming array cannot be modified in the body of the function

Array equality =!= comparison, cannot use < >

1. Declaration & Assignment

Class

Grammar

Copy Code code as follows:

var VarName [n]type//N>=0

e.g.
var a [5]int//[0 0 0 0 0]
var c [2][3]int//Two D

var b int = [5]int{1,2,3,4,5}//Declaration and initialization

A: = [3]int{1,2,3}
B: = [10]int{1,2,3}//first three elements, others 0
c: = [20]int{19:1}//20th element initialized to 1, other default 0
D: = [...] int{4,5,6}//Automatically calculate length
E: = [...] Int{0:1, 1:2, 19:3}//Automatic inference

Two-dimensional array

Copy Code code as follows:

Doublearray: = [2][4]int{[4]int{1,2,3,4}, [4]int{5,6,7,8}}
Easyarray: = [2][4]int{{1,2,3,4}, {1,2,3,4}}

multidimensional [...] [N] The former can be inferred, but the latter must display the assignment
The length of an array is a built-in constant for that array type

Arrlength: = Len (arr)
Note that the array length is also part of the type, so different length arrays are of different types (built-in constants)

That is, [3]int and [4]int are different types, and arrays cannot change length

The assignment between arrays is the assignment of values, that is, when an array is passed as a parameter to the function, it is actually a copy of the array (a copy operation) instead of its pointer, and if you want to pass in the pointer, use the SLICE

2. Element access

Copy Code code as follows:

For i:=0; I < Len (array); i++ {
Fmt. Println (i, array[i])
}

For I, V: = range Array {
Fmt. Println (i, v)
}


You can create an array with new
Copy Code code as follows:

P: = new ([10]int)

Returns a pointer to an array
Pay attention to differentiate

Pointer to array

Copy Code code as follows:

A: = [100]int{}
var p *[100]int = &a

Array of pointers
Copy Code code as follows:

X, y = 1, 2
A: = [...] *int{&x, &y}

Two. Slice

An array slice is like a pointer to an array, but more complex, in fact it has its own data structure, not just pointers (pointers to native arrays + number of elements in an array slice + array slice allocated storage space)

A reference type that always points to an underlying array, and declares that it can be like an array, but does not require a length

Slice is like a structure that contains three elements

A pointer to the slice specified starting position in the array
Length, that is, the length of the slice
The maximum length, which is the length of the slice start position to the last position of the array
1. Declaration & Assignment

Creating with Array

Copy Code code as follows:

var myarray [10]int = [10]int{1,2,3,4,5,6,7,8,9,10}
var myslice []int = Myarray[:5]

A: = [5]int{1,2,3,4,5}
B: = A[2:4]
B: = A[:4]
B: = a[2:]


Re-declare from an array or an existing slice
Copy Code code as follows:

var ar [10]byte {' A ', ' B ', ' C ', ' d ', ' e ', ' f ', ' g ', ' h ', ' I ', ' J '}

var a, b []byte
A = Ar[2:5]
b = Ar[3:5]


Create directly
Copy Code code as follows:

Myslice1: = Make ([]int, 5)
Myslice2: = Make ([]int, 5, 10)//Initial number 5, reserving 10 elements of storage space
Myslice3: = []int{1,2,3,4,5}

2. Element access

Copy Code code as follows:

For i:=0; I<len (Myslice); i++ {
Fmt. Println (i, myslice[i])
}

For I, V: = Range Myslice {
Fmt. Println (i, v)
}

3. Other operations

Size and capacity

Len gets the length of the slice
Cap gets the maximum capacity of the slice

Dynamically increase or decrease elements

Copy Code code as follows:

Append want to append one or more elements to the slice, and then return a slice of the same type as slice

Append
Myslice = Append (Myslice, 1, 2, 3)//Add three elements
Myslice = Append (Myslice, MySlice2)//Add another

Note that append changes the contents of the array referenced by slice, which affects other slice that reference the unified array.
But when there is no space left in the slice, the slice array pointer that dynamically assigns the new array space will point to this space,
The contents of the original array will remain unchanged, and other slice referencing this array are unaffected (pits, possibly introducing bugs)

Content Replication

Copy Code code as follows:

Copy, copy from source slice src to target DST, and return the number of copied elements
Copy (DST, source)//will be copied by a short number

Slice1: = []int{1,2,3,4,5}
Slice2: = []int{5,4,3}

Copy (Slice2, Slice1)//Slice1 top three 1-> 2
Copy (Slice1, SLICE2)//copy Slice2 's top three 2-> 1

Slice

Copy Code code as follows:

Default start position 0,ar[:n] equivalent to ar[0:n]
The second sequence defaults to the array length ar[n:] equivalent to Ar[n:len (AR)]
Get slice from an array directly, can be ar[:]

Slice is a reference type, so when you change the elements, all the other references will change.
Copy Code code as follows:

Aslice = Array[3:7]
Bslice = Aslice[:3]

Three. Map

The concept of a dictionary in Python

Map is unordered, the length is not fixed, the built-in Len can be used for map, can easily modify

1. Declaration & Assignment

Copy Code code as follows:

Map[keytype]valuetype

var m map[string] Personinfo
m = Make (map[string] personinfo[, 100])

var numbers map[string]int
Or
Numbers: = Make (Map[string]int)
numbers["One" = 1


Initialize a dictionary

2. Element access

Copy Code code as follows:

Rating: = map[string]float32 {"c": 5, "Go": 4.5}

Csharprating, OK: = rating["C #"]
If OK {
Fmt. Println ("Get the Value")
} else{
Fmt. PRINTLN ("error")
}


3. Basic operation

assigning values

Copy Code code as follows:

m["1234"] = personinfo{}

Delete
Copy Code code as follows:

Delete (M, "1234")

Four. Other

Make and new operations

Copy Code code as follows:

Make is used for built-in type (Map,slice,channel) memory allocations.

New for various types of memory allocations

New, like a function of the same name in other languages, new (t) allocates a 0-value-filled T-type memory space and returns its address, which is the value of a *t type, which returns a pointer to the 0 value of the newly assigned type T

Make (t, args), you can only create Slice,map,channel and return a type T with an initial value (not 0), rather than a *t. Essentially, the reason these three types are different is that references to data structures must be initialized before they can be used.

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.