Go Language Learning Notes (4) composite types

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

The compound type of the go language, including arrays, slices, and mappings.

values, pointers, and reference types

Typically, a variable in the Go language holds the corresponding value. In other words, we can think of a variable as the value it holds. With some exceptions, channels, functions, methods, mappings, and slices are reference variables that hold references, or variables that hold pointers. Values are copied once when passed to a function or method, which is very inexpensive for Boolean and numeric types, but very expensive for large variables. And the way to copy the parameters, the modified value only modifies the copy, which ensures that the original variable is not modified, but also to some extent, increased the trouble of modifying the original value. Fortunately there are pointers in the go language, and when we use pointers, we pass the memory address of the variable to the function or method each time, which is very inexpensive. And a variable pointed to by the pointer can be modified by the pointer, which makes it convenient to modify the original variable through pointers in the function or in the prevention. The pointer operators in the go language also use the & and * operators, where & is used to fetch addresses, * to dereference, that is to get the value pointed to by the pointer.

Using VIM to create the source file Pointer.go, enter the following source files:

Package Main

Import (

"FMT"

)

Func swap1 (x, Y, p *int) {

If *x > *y {

*x, *y = *y, *x

}

*p = *x * *y

}

Func swap2 (x, y int) (int, int, int) {

If x > y {

X, y = y, X

}

return x, y, x * y

}

Func Main () {

I: = 9

J: = 5

Product: = 0

Swap1 (&i, &j, &product)

Fmt. Println (i, J, product)

A: = 64

B: = 23

A, B, p: = Swap2 (A, B)

Fmt. Println (A, B, p)

}

In the above source, we first created the SWAP1 function, which through the pointer in situ exchange values, while the SWAP2 function by copying the way the value of the variable is exchanged.

The results of the operation are as follows:

$ go Run pointer.go

5 9 45

23 64 1472

Three. Arrays and slices

1. Arrays

The go language array is a fixed-length sequence in which the elements are of the same type. A multidimensional array can be created simply by using its own array of elements. The elements of the array are indexed using the action symbol [], and the index starts at 0 and ends with Len (array)-1. Arrays are created using the following syntax:

    • [Length] Type
    • N Type{value1, value2, ..., Valuen}
    • [...] Type{value1, value2, ..., Valuen}

If you use the ... (ellipsis) operator, the Go language automatically calculates the length of the array for us. In any case, the length of an array is fixed and cannot be modified. The length of the array can be obtained using the Len () function. Since the length of the array is fixed, the length and capacity of the array are the same, so the return value of the cap () and Len () function is the same for arrays. Arrays can also be sliced using the same syntax as slices, except that the result is a slice, not an array. Similarly, arrays can be accessed using range for indexing.

2. Slicing

In general, the go language slices are more flexible, powerful and convenient than arrays. The array is passed by value (that is, a copy of the pass), and the slice is a reference type, and the cost of passing the slice is very small, and it is fixed-length. And the array is fixed-length, and the slices can be resized. The syntax for creating slices is as follows:

    • Make ([]type, length, capacity)
    • Make ([]type, length)
    • []type{}
    • []type{value1, Value2, ..., Valuen}

Built-in function make () is used to create slices, mappings, and channels. When used to create a slice, it creates a hidden array initialized to a value of 0, and then returns a slice that references the hidden array. The hidden array, like all arrays in the go language, is fixed length, and if created using the first syntax, its length is the slice's capacity capacity, and if it is the second syntax, its length is recorded as the length of the slice. The capacity of a slice is the length of the hidden array, and its length is any value that does not exceed that capacity. You can also increase the capacity of a slice by using the built-in function append (). Slices can support the following actions:

In our practice, using VIM to create the source file Slice_array.go, enter the following code:

Package Main

Import (

"FMT"

)

Func Main () {

A: = [...] Int{1, 2, 3, 4, 5, 6, 7}

Fmt. Printf ("Len and cap of array%v is:%d and%d\n", A, Len (a), Cap (a))

Fmt. Printf ("Item in array:%v is:", a)

For _, Value: = Range a {

Fmt. Printf ("% d", value)

}

Fmt. Println ()

S1: = A[3:6]

Fmt. Printf ("Len and cap of Slice:%v is:%d and%d\n", S1, Len (S1), Cap (S1))

Fmt. Printf ("Item in Slice:%v is:", S1)

For _, Value: = Range S1 {

Fmt. Printf ("% d", value)

}

Fmt. Println ()

S1[0] = 456

Fmt. Printf ("item in array changed after changing slice:%v is:", S1)

For _, Value: = Range a {

Fmt. Printf ("% d", value)

}

Fmt. Println ()

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

S2[4] = 5

Fmt. Printf ("Len and cap of Slice:%v is:%d and%d\n", S2, Len (S2), Cap (S2))

Fmt. Printf ("Item in Slice%v is:", S2)

For _, Value: = Range S2 {

Fmt. Printf ("% d", value)

}

Fmt. Println ()

}

In the above code, we first create an array whose length is computed automatically by the Go language (ellipsis syntax), then we create the slice S1 from array a by slicing, and then we change the value of the first position of the slice, and we find that the values in array a also change. Finally, we created a slice with the make () function, which has a length and capacity of 10 and 20, and can also find that the Go language automatically assigns uninitialized items to 0 values. Run the code output as follows:

$ go Run slice_array.go

Len and cap of array [1 2 3 4 5 6 7] Is:7 and 7

Item in array: [1 2 3 4 5 6 7] is:1 2 3 4 5 6 7

Len and cap of Slice: [4 5 6] Is:3 and 4

Item in Slice: [4 5 6] is:4 5 6

Item in array changed after changing slice: [456 5 6] is:1 2 3 456 5 6 7

Len and cap of Slice: [0 0 0 0 5 0 0 0 0 0] is:10 and 20

item in slice [0 0 0 0 5 0 0 0 0 0] is:0 0 0 0 5 0 0 0 0 0

Four. Mapping (map)

Mapping in the Go language is a built-in data structure that stores an unordered collection of key = value pairs, whose capacity is limited only by machine memory, similar to a dictionary in Python. All keys in a map are unique and must be types that support the = = and! = operators, and most of the basic types of Go languages can be mapped as keys, but slices, arrays that cannot be used for comparison, structs (members of these types or fields do not support = = and! =) Operation) or a custom type based on these cannot be a key. However, any type can be used as a value. Mappings are reference types, so delivery is very inexpensive.

Mappings in the go language can be created using the following usage:

    • Make (Map[keytype]vauletype, initialcapacity)
    • Make (Map[keytype]valuetype)
    • map[keytype]valuetype{}
    • Map[keytype]valuetype{key1:value1, Key2:value2, ..., Keyn:valuen}

Built-in function make () can be used to create slices, mappings, and channel (channels). When you create a map with make (), you actually get an empty map, and if you specify a capacity (initialcapacity), you will pre-request enough memory, and as more entries are added, the mapping will expand the field. The mapping supports the following operations:

Grammar

Meaning

M[k] = V

Use the key k to assign the value to the mapping m. If k already exists in the mapping m, discard the previous value

Delete (M, k)

Remove the key k and its associated values from the mapping m and do nothing if K does not exist

V: = m[k]

The value corresponding to the key k is obtained from the mapping m and assigned to V. If K does not exist, assign a value of 0 to the map type V

V, found: = M[k]

The value corresponding to the key k is obtained from the mapping m and assigned to V and the value of found is assigned to false. If K does not exist, then found is false

Len (M)

Returns the items in the map m

K: = range m

Traverse the keys in the map m

K, V: = range m

Traversing keys and values in a map at the same time

Next we practice. Use Vim to create the source file Map_t.go Enter the following code:

Package Main

Import (

"FMT"

)

Func Main () {

Shiyanlou: = Make (map[string]string)//Same as Map[string]string

shiyanlou["Golang"] = "Docker"

shiyanlou["python"] = "flask web Framework"

shiyanlou["Linux"] = "SYS Administrator"

Fmt. Print ("Traverse All Keys:")

For key: = Range Shiyanlou {//traversed all keys of the map

Fmt. Printf ("% s", key)

}

Fmt. Println ()

Delete (Shiyanlou, "Linux")//Remove the key "Linux" and its value from the map

shiyanlou["Golang"] = value of "Beego Web Framework"//Update Key "Golang"

V, found: = shiyanlou["Linux"]

Fmt. Printf ("Found key \" Linux\ "Yes or False:%t, value of key \" linux\ ": \"%s\ "", Found, V)

Fmt. Println ()

Fmt. Println ("Traverse all keys/values after changed:")

For k, V: = range Shiyanlou {//traversed all the key/value pairs of the map

Fmt. Printf ("\"%s\ ": \"%s\ "\ n", K, V)

}

}

In the above code, we first created a mapping and then assigned 3 key/value pairs, then we traversed all the keys in the map, removed a key from the map using the Delete () function, and then traversed the map again. The mapping operation is very simple, a lot of practice can.

The results of the operation are as follows:

$ go Run map_t.go

Traverse all Keys:golang python Linux

Found key "Linux" Yes or False:false, value of key "Linux": ""

Traverse all keys/values after changed:

"Golang": "Beego Web Framework"

"Python": "Flask Web Framework"

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.