A concise summary of the arrays, Slices, Maps, range operations of the Go Language primer _golang

Source: Internet
Author: User
Tags apd array length

Arrays: Arrays

In the go language, array array is a set of ordered elements of a certain length.

Copy Code code as follows:

Package Main

Import "FMT"

Func Main () {

Here we created an array of length 5. The initial value of this set of arrays is zero-valued. The whole type is 0.
var a [5]int
Fmt. Println ("EMP:", a)

Can be assigned by array[index] = value syntax
A[4] = 100
Fmt. Println ("Set:", a)
Fmt. Println ("Get:", A[4])

The built-in Len function returns the array length
Fmt. Println ("Len:", Len (a))

Declare the default initial value of an array through this syntax
B: = [5]int{1, 2, 3, 4, 5}
Fmt. Println ("DCL:", b)

The array type is one-dimensional, but you can create a multidimensional array structure by combining
var Twod [2][3]int
For I: = 0; I < 2; i++ {
For j: = 0; J < 3; J + + {
TWOD[I][J] = i + j
}
}
Fmt. Println ("2d:", Twod)
}


$ go Run arrays.go
EMP: [0 0 0 0 0]
Set: [0 0 0 0 100]
get:100
Len:5
DCL: [1 2 3 4 5]
2d: [[0 1 2] [1 2 3]]

Slices: Slicing

Slices is a key data type in the go language that has a stronger access interface than an array (arrays).

Copy Code code as follows:

Package Main

Import "FMT"

Func Main () {

Unlike an array (arrays), the type of slices is the same as the contained element type (not the number of elements). Use the built-in make command to construct an empty slice object with a non-zero length. Here we create a string that contains 3 characters. (initialized to 0 value zero-valued)
S: = make ([]string, 3)
Fmt. Println ("EMP:", s)

We can set and read like arrays.
S[0] = "a"
S[1] = "B"
S[2] = "C"
Fmt. Println ("set:", s)
Fmt. Println ("Get:", s[2])

The length obtained is the length of the setting at that time.
Fmt. Println ("Len:", Len (s))

Relative to these basic operations, slices supports some of the more complex features. One is the built-in append that can add one or more values to an existing slice object. Note You want to reassign the returned append object to get the most recent slice object with the added element.
s = Append (S, "D")
s = Append (S, "E", "F")
Fmt. Println ("APD:", s)

Slices can also be copied. Here we copy S to C, which is consistent in length.
c: = Make ([]string, Len (s))
Copy (c, s)
Fmt. Println ("cpy:", c)

Slices supports the "slice" operation, which is syntactically Slice[low:high] (that is, the segment value in the Intercept slice). The following code will get these characters: s[2], s[3], and s[4].
L: = S[2:5]
Fmt. Println ("SL1:", L)

Intercept from start to every 5 characters (except values)
L = S[:5]
Fmt. Println ("SL2:", L)

Intercept from the second (including) character to the last
L = s[2:]
Fmt. Println ("SL3:", L)

We can put declarations and assignments on one line.
T: = []string{"G", "H", "I"}
Fmt. Println ("DCL:", T)

Slices can be grouped into multidimensional arrays. A one-dimensional slices object can be unequal in length, unlike a multidimensional array.
Twod: = Make ([][]int, 3)
For I: = 0; I < 3; i++ {
Innerlen: = i + 1
Twod[i] = make ([]int, Innerlen)
For j: = 0; J < Innerlen; J + + {
TWOD[I][J] = i + j
}
}
Fmt. Println ("2d:", Twod)
}

Note that slices and arrays are two different types of data, but their fmt. Println are similar in print mode.

Copy Code code as follows:

$ go Run slices.go
EMP: []
Set: [a B c]
Get:c
Len:3
APD: [a B c D E F]
CPY: [a b c D E F]
SL1: [C D E]
SL2: [a b c D e]
SL3: [C D E F]
DCL: [g H i]
2d: [[0] [1 2] [2 3 4]]

Take a look at this article and see how the Go team designed and implemented slices in go.

Maps: Key-value pairs

Maps is the associated data type in the Go language (sometimes referred to as a hash table [hashes] or dictionary [dicts] in other languages)

Copy Code code as follows:

Package Main

Import "FMT"

Func Main () {

Use built-in make to build an empty map,make (map[key type) value type
M: = Make (Map[string]int)

Set key/value pairs using the classic Name[key] = Val syntax.
m["K1"] = 7
m["K2"] = 13

The print map will output all the key values in the
Fmt. PRINTLN ("Map:", m)

Gets the value of a key
V1: = m["K1"]
Fmt. Println ("v1:", v1)

The Len function gets the number of key/value pairs in the map
Fmt. Println ("Len:", Len (m))

To remove a key/value pair from a map using the built-in delete function
Delete (M, "K2")
Fmt. PRINTLN ("Map:", m)

The optional second return value can indicate whether the value of this key is included in the map. Avoid ambiguity caused by null value 0 or "".
_, PRs: = m["K2"]
Fmt. Println ("PRS:", PRS)

You can also complete the declaration and assignment on one line.
N: = map[string]int{"foo": 1, "Bar": 2}
Fmt. PRINTLN ("Map:", N)
}

Note When using FMT. The output format of the map is Map[k:v k:v] when printed println.

Copy Code code as follows:

$ go Run maps.go
Map:map[k1:7 K2:13]
V1:7
Len:2
Map:map[k1:7]
Prs:false
Map:map[foo:1 Bar:2]

Range: Range

Range can be enumerated on a variety of data structures. Let's look at how to use the previous data structure.

Copy Code code as follows:

Package Main

Import "FMT"

Func Main () {

This is how we use range to find a slice and. Using an array is similar to this
Nums: = []int{2, 3, 4}
Sum: = 0
For _, num: = Range Nums {
sum + = num
}
Fmt. Println ("sum:", sum)

Using range on an array will pass in the index and value two variables. The above example we do not need to use the number of the element, so we use the whitespace "_" omitted. Sometimes we really need to know its index.
For i, num: = Range Nums {
If num = 3 {
Fmt. Println ("Index:", i)
}
}

Range can also be used on the key value pairs of a map.
KVS: = map[string]string{"A": "Apple", "B": "Banana"}
For k, V: = range KVS {
Fmt. Printf ("%s->%s\n", K, V)
}

Range can also be used to enumerate Unicode strings. The first argument is the index of the character, and the second is the character (the value of Unicode) itself.
For I, c: = Range ' Go ' {
Fmt. Println (i, C)
}
}


$ go Run range.go
Sum:9
Index:1
A-> apple
b-> Banana
0 103
1 111

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.