An array of Golang, Slice,map

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



One, ==========================array array ===================================

An index can only be an int integer, so no matter how many dimensional array indexes are integers slice is a dynamic array index and the integer map is a key so it can be an integer or a string type

Note the difference between the slice and the declaration: When declaring an array, the length of the array is indicated in square brackets or used ... The length is automatically calculated, and when the slice is declared, there are no characters in the square brackets.

ARR1: = [10]int{1,2,3,4}//array, length 10, only 4 elements specified, other element values default to 0

ARR2: = [...] String{"A", "B", "C"}//array, length adaptive, here length is 3

S1: = []int{1,2,3,4}//slice, current length is 4, may be dynamically added by append to the number of elements


How arrays are declared

ARR1: = [10]int{1,2,3,4}//array, length 10, only 4 elements specified, other element values default to 0

The index is 0:1 1:2 2:3 3:4 4:0 5:0 ..... 9:0


ARR1: = [10]string{"1", "2", "3", "4"}//array, length 10, only 4 elements specified, other element values default to "" Empty string

Inside index is 0: "1" 1: "2" 2: "3" 3: "4" 4: "0" 5: "" ..... 9: ""


ARR2: = [...] String{"A", "B", "C"}//array, length adaptive, here length is 3

ARR3: = Make ([]int, ten)//made to create a memory length of 10 elements is 0


var arr4 [5]int

Arr4[0] = 9

arr4=[5]int{5,5,5}//[5 5 5 0 0]


You can create an array with new () and return an array pointer.

Func Test (a *[10]int) {

A[2] = 100//Direct operation with a pointer without pressure.

}

Func Main () {

var a = new ([10]int)//return pointer.

Test (a)

Fmt. Println (A, Len (a))

}

Output Result:


&[0 0 100 0 0 0 0 0 0 0] 10



Multidimensional arrays


A: = [2][2]int{{}, {3,4}}

B: = [2][2]str{{"1", "2"}, {"3", "4"}}


Func Main () {

var a = [3][2]int{[...] Int{1, 2}, [...] Int{3, 4}}

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

c: = [...] [2]int{{1, 2}, {3, 4}, {5, 6}}//The second dimension cannot be "...".

C[1][1] = 100

Fmt. Println (A, "\ n", B, "\ n", C, Len (c), Len (C[0]))

}


Array comparison

println ([1]string{"a"} = = [1]string{"A"})


An array is a value type, which means that the entire array memory is copied for value passing. Use slice or pointers instead.


Second, ==========================slice Slice ===================================

A slice is a collection of pointers to the array of values that the slice is taken out of.


An array index can only be an int integer, so no matter how many dimensional array indexes are integers slice is a dynamic array index and the integer map is a key so it can be an integer or a string type

Note the difference between the slice and the declaration: When declaring an array, the length of the array is indicated in square brackets or used ... The length is automatically calculated, and when the slice is declared, there are no characters in the square brackets.


Slice declaration

s: = []int{0, 1, 2}


You cannot use new (), but it should be make ([]t, Len, CAP). Because in addition to allocating memory, you need to set the related properties. Such as

If the cap parameter is ignored, Cap = Len.


Func Main () {

S1: = Make ([]int, 10)//equals [10]int{...} [:]

S1[1] = 100

Fmt. Println (S1, Len (S1), Cap (S1))

S2: = Make ([]int, 5, 10)

S2[4] = 200

Fmt. PRINTLN (S2, len (S2), Cap (S2))

}

Output:


[0 100 0 0 0 0 0 0 0 0] 10 10

[0 0 0 0 200] 5 10


You can add new elements to the tail of slice with append (), which are saved to the underlying array. Append does not affect the properties of the original slice, it returns the new slice object after the change. If the cap limit is exceeded, the underlying array is reassigned.


==========================maps Dictionary ===================================

Reference types, similar to Python dict, do not guarantee key/value storage order. 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.

The map lookup operation is much faster than a linear search, but it is approximately 100x or so slower than an ordinal access array or slice. Most of the time, its operating performance is slightly better than Python Dict, C + + Map.


Func Test (d map[string]int) {

d["x"] = 100

}

Func Main () {

var d = map[string]int{"A": 1, "B": 2};

D2: = map[int]string{1: "A", 2: "B"};

Test (d)

Fmt. Println (d, D2)

D3: = Make (map[string]string)

d3["name"] = "Jack"

Fmt. Println (D3, Len (D3))

}

Output:


Map[a:1 b:2 x:100] map[1:a 2:b]

Map[name:jack] 1



Make Array/struct key an example.


Type User struct {

Name string

}

Func Main () {

A: = [2]int{0, 1}

B: = [2]int{0, 1}

D: = map[[2]int]string {A: "SSSs"}

Fmt. Println (d, D[b])

U: = user{"User1"}

U2: = u

D2: = map[user]string {u: "xxxx"}

Fmt. Println (D2, D2[U2])

}

Output:


Map[[0 1]:ssss] SSSs

MAP[{USER1}:XXXX] xxxx



The type of value is very free, and can be completely anonymous or an empty interface.


Type User struct {

Name string

}

Func Main () {

I: = 100

D: = map[*int]struct{x, y float64} {&i: {1.0, 2.0}}

Fmt. Println (d, D[&i], D[&I].Y)

D2: = map[interface{}]string {"A": "1", 1: "Ssssss"}

D2: = map[string]interface{} {"A": 1, "B": user{"user1"}}

Fmt. Println (D2, d2["B"]. ( User). Name)

}

Output:


Map[0x42132018:{1 2}] {1 2} 2

Map[a:1 B:{user1}] User1



When you create a map with make (), providing a reasonable initial capacity can help reduce the number of memory allocations for subsequent new operations. When needed, the map will ⾃ the expansion capacity.

Common judgment and delete operations:


Func Main () {

var d = map[string]int{"A": 1, "B": 2};

V, OK: = d["B"]//key B exists, v = ["B"], OK = True

Fmt. Println (V, OK)

v = d["C"]//Key C does not exist, V = 0 (default)

Fmt. Println (v)//To determine whether a key exists, it is recommended to use the OK idiom mode.

D["C"] = 3//Add or modify

Fmt. Println (d)

Delete (d, "C")//Remove. Deleting a nonexistent key does not raise an error.

Fmt. Println (d)

}

Output:


2 true

0 false

Map[a:1 C:3 B:2]

Map[a:1 B:2]



Iterator usage:

The Go 1.1 HashMap iteration starts at a random bucket. However, it stores up to 8 key/value pairs in a bucket.

And within a bucket, HashMap iteration always returns the values in the same order.


Func Main () {

D: = map[string]int{"A": 1, "B": 2};

For k, V: = range D {//Get key, value

println (k, "=", V)

}

For k: = range D {//Get key only

println (k, "=", D[k])

}

}

Only a "copy of the temporary value" returned by Map[key], modifying its own state has no meaning, can only be re-assigned value or use a pointer to modify the referenced memory.


Type User struct {

Id int

Name string

}

Func Main () {

Users: = map[string]user{

"A": User{1, "user1"},

}

Fmt. Println (Users)

Error:cannot Assign to Users["a"]. Name

Users["a"]. Name = "Jack"

Re value assignment

U: = users["a"]

U.name = "Jack"

Users["a"] = U

Fmt. Println (users["a"])

Change ⽤ pointer type

Users2: = map[string]*user{

"A2": &user{2, "User2"},

}

users2["A2"]. Name = "Tom"

Fmt. Println (users2["A2"])

}

Output:


Map[a:{1 User1}]

{1 Jack}

&{2 Tom}



You can safely delete and insert a new dictionary entry during the for range iteration.


Func Main () {

D: = map[string]int {"B": 2, "C": 3, "E": 5}

For k, V: = Range D {

println (k, v)

if k = = "B" {Delete (d, k)}

if k = = "C" {d["a"] = 1}

}

Fmt. Println (d)

}

Output:


C 3

B 2

E 5

Map[a:1 C:3 E:5]



Note: When map is a parameter, the pointer is copied directly.


Related Article

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.