A detailed description of the composite type in the Go language _golang

Source: Internet
Author: User
Tags arrays integer numbers

Golang composite types include: structs, arrays, slices, Maps.

1, array

Array

The array in Golang differs greatly from the array in the C language, which is more like an array in Pascal. (Slice, next topic, some like an array in C language)

Copy Code code as follows:

var ar [3]int

Declares that AR is an array of three integer numbers, all elements initialized to 0.

Size is an integral part of a type.

The built-in function Len can be used to get the array size:

Copy Code code as follows:

Len (AR) = 3

Array is a value type

The array in Golang is a value, not an implicit pointer in the C language. You can get the address of the array and generate a pointer to the array (for example, efficiently passing it to a function):

Copy Code code as follows:

Func f (A [3]int) {fmt. Println (A)}
Func fp (a *[3]int) {fmt. Println (A)}

Func Main () {
var ar [3] int
F (AR)//pass a copy of AR
FP (&ar)//pass a pointer to AR
}

Output results:

Copy Code code as follows:

[0 0 0]

&[0 0 0]

Array literal value

All conforming types have the same value creation syntax. As an example of an array, the syntax is as follows:

An array of 3 integers:

Copy Code code as follows:

[3]int{1, 2, 3}

An array of 10 integers, the first three elements are not 0:

Copy Code code as follows:

[10]int{1, 2, 3}

Don't want to count? Use... Representative Length:

Copy Code code as follows:

[...] Int{1, 2, 3}

Do not want to initialize all values? Using Key:value Pairs:

Copy Code code as follows:

[10]int{2:1, 3:1, 5:1, 7:1}

Pointer to array literal value

You can get the address of an array literal, so you can get a pointer to the new array instance:

Copy Code code as follows:

Func fp (a *[3]int) {fmt. Println (A)}
Func Main () {
For I: = 0; I < 3; i++ {
FP (&[3]int{i, I*i, i*i*i})
}
}

Output results:

Copy Code code as follows:

&[0 0 0]
&[1 1 1]
&[2 4 8]

2. Slice (Slice)

Slice

A slice is a reference to a paragraph in an array.

Slices are more widely used than normal arrays.

Slicing is a very low price to use.

A slice type is like an array type with no size:

Copy Code code as follows:

var a []int

The built-in Len (a) can return the number of elements in the slice.

By slicing through an array or slice, we can create a new slice:

Copy Code code as follows:

A = Ar[7:9]

The valid subscript values for a (a in the example above) are 0 and 1;len (a) = = 2.

Sliced shorthand

When you slice arrays, the first subscript value defaults to 0:

AR[:N] is equivalent to a[0:n].

The second subscript value defaults to Len (array/slice):

Ar[n:] equivalent to Ar[n:len (AR)].

So when you create slices from an array:

ar[:] equivalent to Ar[0:len (AR)].

Slice reference Array

Conceptually:

Copy Code code as follows:

Type Slice struct {
Base *elemtype//pointers to 0th elements
Number of elements in Len Int//slices
Cap int//slices can hold the number of elements
}

Array:

Copy Code code as follows:

Ar:7 1 5 4 3 8 7 2 11 5 3

Slice:

Copy Code code as follows:

A = Ar[7:9]: base = &ar[7] (pointing to 2 in ar) len = 2 Cap = 4

Create slices

The slice literal value looks like an array literal with no specified size:

Copy Code code as follows:

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

The code above creates an array of length 5 and creates a slice to reference the array.

We can use the built-in make function to assign a slice (the bottom is actually an array):

Copy Code code as follows:

var s100 = make ([]int, MB)//slice:100 INTs

Why use make rather than new? Because we need to create slices, not just to allocate memory. Note Make ([]int, 10) returns []int, and New ([]int) returns to *[]int.

Use make to create slices, maps, and channel.

Slice capacity

A slice is a reference to the underlying array. So there are elements in the array that are not in the range referenced by the slice.

The built-in function cap (capacity) is used to report how long a slice may grow.

Copy Code code as follows:

var ar = [10]int{0,1,2,3,4,5,6,7,8,9}
var a = Ar[5:7]//referencing child array {5,6}

Len (a) = 2,cap (a) = 5, now we can re-slice:

Copy Code code as follows:

A = A[0:4]//referencing child array {5,6,7,8}

Len (a) is now 4, while Cap (a) is still 5.

resizing slices

Slices can be used as an array for growth. Use make to assign a slice and specify its length and capacity. When it comes to growth, we can do a new slice:

Copy Code code as follows:

var sl = Make ([]int, 0, 100)//Length 0, Volume 100
Func appendtoslice (i int, sl []int) []int {
If Len (SL) = = Cap (SL) {error (...)}
N: = Len (SL)
SL = sl[0:n+1]//length increased by 1
Sl[n] = i
Return SL
}

Therefore, the length of SL is always the number of elements, but its capacity can be increased according to need.

This is a very small price to pay, and it is the idiom in the go language.

Slicing is a small price to use

You can freely allocate and resize slices according to your needs. Their delivery takes only a small price;

Remember that they are references, so the underlying storage can be modified.

For example, I/O uses slices instead of counting:

Copy Code code as follows:

Func Read (fd int, b []byte) int
var buffer [100]byte
For I: = 0; I < 100; i++ {
Fills a byte in buffer every time
Read (FD, buffer[i:i+1])//No allocation here
}

Divide a buffer:

Copy Code code as follows:

Header, Data: = Buf[:n], Buf[n:]

Strings can also be sliced and are similar in efficiency.

3, Maps

Maps

A map is another type of reference. They are declared in this way:

Copy Code code as follows:

var m map[string]float64

Here we declare a map, the type of the index key is string, and the value type is float64. This is similar to the type *map<string in C + +, float64>.

Returns the number of keys for a given map M,len (m).

The creation of a map

As with creating a slice, a map variable is a null reference; Before you can use it, you should put something inside it.

Three kinds of ways:

1) literal value: comma-delimited list of key:value pairs

Copy Code code as follows:

m = map[string]float64{"1": 1, "PI": 3.1415}

2) Create
Copy Code code as follows:

m = Make (Map[string]float64)//Do not new

3) Assigning value
Copy Code code as follows:

var M1 map[string]float64
M1 = m//M1 and M now refer to the same map

Map Index

(the next few examples are all used:

Copy Code code as follows:

m = map[string]float64{"1": 1, "PI": 3.1415})

Accesses an element, and if the element does not exist, the 0 value of the corresponding map value type is obtained:
Copy Code code as follows:

One: = m["1"]
Zero: = m["Not Present"]//zero is set to 0.0.

Sets the value of an element (two times the setting will be updated to the latest value)
Copy Code code as follows:

m["2"] = 2
m["2"] = 3//Mental confusion

Testing for the existence of

To test whether a key exists in a map, we can use a multiple-valued "comma, om" form:

Copy Code code as follows:

m = map[string]float64{"1": 1, "PI": 3.1415}

var value float64
var present bool

Value, present = M[x]

or by convention:

Copy Code code as follows:

Value, OK: = m[x]//"Comma OK" form

If there is an X key in the map, the Boolean variable is set to the value that True;value will be assigned to the key in the map. Instead, the Boolean variable is set to a value of 0 that False,value is set to the corresponding value type.

Delete

You can delete a value from a map by using a multivariate assignment:

Copy Code code as follows:

m = map[string]float64{"1": 1.0, "PI": 3.1415}

var keep bool
var value float64
var x string = f ()

M[x] = V, keep

If the value of Keep is true, the V is assigned to the map, or the key x in the map is deleted if Keep is false. So delete a key:

Copy Code code as follows:

M[x] = 0, false//remove X from map

The above deletion in go 1 has been canceled and replaced by Delete (M, x).

For and Range

For arrays, slices, and maps (and more types that we will see in Part Three), the For Loop provides a special syntax for iterating over the elements in them.

Copy Code code as follows:

M: = map[string]float64{"1": 1.0, "PI": 3.1415}

For key, Value: = range m {
Fmt. Printf ("key%s, value%g\n", key, value)
}

With only one variable, we can get key:

Copy Code code as follows:

For key = range M {
Fmt. Printf ("Key%s\n", key)
}

A variable can be assigned a value or declaration with: =.

For arrays and slices, in this way we can get the subscript of the element and the value of the element.

Use range for string

When you use a for range with a string, the element of the actual iteration is a Unicode code point, rather than a byte (for bytes, you can use []byte or use a standard for statement). Let's assume that the string package

Contains characters that are encoded using UTF-8.

Loop below:

Copy Code code as follows:

S: = "[\u00ff\u754c]"
For I, c: = Range S {
Fmt. Printf ("%d:%q", I, c)//%q for ' quoted '
}

Output: 0: ' [' 1: ' Y ' 3: ' Boundary ' 6: '] '

If the wrong UTF-8 code point is encountered, the character is set to U+FFFD, and the subscript moves one byte backward.

4, Structs

Structs

For the struct in go, you should feel very familiar: a simple data field declaration.

Copy Code code as follows:

var p struct {
X, y float64
}

More commonly used are:

Copy Code code as follows:

Type point struct {
X, y float64
}
var p point

struct allows programmers to define memory layouts.

struct is a value type

struct is a value type, and new (Structtype) returns a pointer to a 0 value (the allocated memory is set to 0).

Copy Code code as follows:

Type point struct {
X, y float64
}
var p point
p.x = 7
P.Y = 23.4
var pp *point = new (point)
*PP = P
pp.x = Pi//(*PP). The grammatical sugars of X

For a struct pointer, there is no-> symbol available. Go provides an indirect way.

To create a structural body

A struct is a value type, so you can create a struct variable of 0 by simply declaring it.

You can also use new to create a struct.

Copy Code code as follows:

var p point//0 value
PP: = new (point)/idiomatic method

The structure literal syntax is also as expected:

Copy Code code as follows:

p = point{7.2, 8.4}
p = point{y:8.4, x:7.2}
pp = &point{7.2, 8.4}/idiomatic method
pp = &point{}//also idiomatic, = = new (point)

As well as arrays, the address of the structural body literal is obtained, and the address of the new structure is obtained.

These examples are all constructors.

Export types and fields

It is visible only when the first letter of the name is capitalized in the field (and method) of the struct body.

Private Types and fields:

Copy Code code as follows:

Type point struct {x, y float64}

Export Types and fields:
Copy Code code as follows:

Type point struct {X, Y float64}

Export type and private type mixed fields:
Copy Code code as follows:

Type point struct {
X, Y float64//exported
Name string//not exported
}

You can even create a private type with an exported field. (Practice: When will it be useful?) )

Anonymous fields

In a structure, you can declare a field without a name, such as another struct type. These fields are called anonymous fields. They look like the inner structure is simply inserted or "embedded" into

The outer structure of the body.

This simple mechanism provides a way to inherit existing implementations from other types.

Here is an example.

An anonymous structural body field:

Copy Code code as follows:

Type A struct {
AX, ay int
}

Type B struct {
A
BX, by Float64
}

B looks like there are four fields ax, Ay, BX and by. B can be seen as {ax, ay int; bx, by float64}.

Then the word value of B must provide details:

Copy Code code as follows:

B: = B{a{1, 2}, 3.0, 4.0}
Fmt. Println (B.AX, B.ay, B.BX, b.by)

Output 1 2 3 4

Anonymous field with type as name

Anonymous fields are not only simple to insert into these fields, they are richer in meaning: B also has field a. An anonymous field looks like a field whose name is its type.

Copy Code code as follows:

B: = b{a{1, 2}, 3.0, 4.0}
Fmt. Println (B.A)

Output: {1 2}. If a is from another package, this field is still called a.

Copy Code code as follows:

Import "Pkg"
Type C struct {pkg. A
...
c: = c {pkg. A{1, 2}}
Fmt. PRINTLN (C.A)//Not C.PKG.A

Anonymous fields of any type

Any named type or pointer to a named type can be used as an anonymous field. They can appear anywhere in the structure body.

Copy Code code as follows:

Type C struct {
X float64
Int
String
}
c: = c{3.5, 7, "Hello"}
Fmt. Println (c.x, C.int, c.string)

Output: 3.5 7 Hello

Conflict and shadowing

If two fields have the same name (possibly an inherited type name), the code follows the following rules:

1 The outer name obscures the inner layer's name. This provides a way to write back the section/method.
2 If the same name appears on the same level, if the name is used, then it would be a mistake. (if not used, no error occurs)

Ambiguity is not a rule that can be solved and must be fixed.

Examples of conflicts

Copy Code code as follows:

Type a struct {a int}
Type B struct {a, b int}
Type C struct {A; B
var c c

There will be an error using C.A. It's C. A.A or C.B.A?

Copy Code code as follows:

Type D struct {b; b float64}
var d d

There is no problem with using d.b: It is a float64 type variable, not a d.b.b. To get the inner layer B, use D. B.b.

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.